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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
dropbox/godropbox | rate_limiter/rate_limiter.go | SetMaxQuota | func (l *rateLimiterImpl) SetMaxQuota(q float64) error {
if q < 0 {
return errors.Newf("Max quota must be non-negative: %f", q)
}
l.mutex.Lock()
defer l.mutex.Unlock()
l.maxQuota = q
if l.quota > q {
l.quota = q
}
if l.maxQuota == 0 {
l.cond.Broadcast()
}
return nil
} | go | func (l *rateLimiterImpl) SetMaxQuota(q float64) error {
if q < 0 {
return errors.Newf("Max quota must be non-negative: %f", q)
}
l.mutex.Lock()
defer l.mutex.Unlock()
l.maxQuota = q
if l.quota > q {
l.quota = q
}
if l.maxQuota == 0 {
l.cond.Broadcast()
}
return nil
} | [
"func",
"(",
"l",
"*",
"rateLimiterImpl",
")",
"SetMaxQuota",
"(",
"q",
"float64",
")",
"error",
"{",
"if",
"q",
"<",
"0",
"{",
"return",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"q",
")",
"\n",
"}",
"\n\n",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"l",
".",
"maxQuota",
"=",
"q",
"\n",
"if",
"l",
".",
"quota",
">",
"q",
"{",
"l",
".",
"quota",
"=",
"q",
"\n",
"}",
"\n\n",
"if",
"l",
".",
"maxQuota",
"==",
"0",
"{",
"l",
".",
"cond",
".",
"Broadcast",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // This sets the leaky bucket's maximum capacity. The value must be
// non-negative. | [
"This",
"sets",
"the",
"leaky",
"bucket",
"s",
"maximum",
"capacity",
".",
"The",
"value",
"must",
"be",
"non",
"-",
"negative",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L155-L173 | train |
dropbox/godropbox | rate_limiter/rate_limiter.go | QuotaPerSec | func (l *rateLimiterImpl) QuotaPerSec() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.quotaPerSec
} | go | func (l *rateLimiterImpl) QuotaPerSec() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.quotaPerSec
} | [
"func",
"(",
"l",
"*",
"rateLimiterImpl",
")",
"QuotaPerSec",
"(",
")",
"float64",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
".",
"quotaPerSec",
"\n",
"}"
] | // This returns the leaky bucket's fill rate. | [
"This",
"returns",
"the",
"leaky",
"bucket",
"s",
"fill",
"rate",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L176-L181 | train |
dropbox/godropbox | rate_limiter/rate_limiter.go | SetQuotaPerSec | func (l *rateLimiterImpl) SetQuotaPerSec(r float64) error {
if r < 0 {
return errors.Newf("Quota per second must be non-negative: %f", r)
}
l.mutex.Lock()
defer l.mutex.Unlock()
l.quotaPerSec = r
return nil
} | go | func (l *rateLimiterImpl) SetQuotaPerSec(r float64) error {
if r < 0 {
return errors.Newf("Quota per second must be non-negative: %f", r)
}
l.mutex.Lock()
defer l.mutex.Unlock()
l.quotaPerSec = r
return nil
} | [
"func",
"(",
"l",
"*",
"rateLimiterImpl",
")",
"SetQuotaPerSec",
"(",
"r",
"float64",
")",
"error",
"{",
"if",
"r",
"<",
"0",
"{",
"return",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"r",
")",
"\n",
"}",
"\n\n",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"l",
".",
"quotaPerSec",
"=",
"r",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // This sets the leaky bucket's fill rate. The value must be non-negative. | [
"This",
"sets",
"the",
"leaky",
"bucket",
"s",
"fill",
"rate",
".",
"The",
"value",
"must",
"be",
"non",
"-",
"negative",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L184-L195 | train |
dropbox/godropbox | rate_limiter/rate_limiter.go | Quota | func (l *rateLimiterImpl) Quota() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.quota
} | go | func (l *rateLimiterImpl) Quota() float64 {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.quota
} | [
"func",
"(",
"l",
"*",
"rateLimiterImpl",
")",
"Quota",
"(",
")",
"float64",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"l",
".",
"quota",
"\n",
"}"
] | // This returns the current available quota. | [
"This",
"returns",
"the",
"current",
"available",
"quota",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L198-L202 | train |
dropbox/godropbox | rate_limiter/rate_limiter.go | setQuota | func (l *rateLimiterImpl) setQuota(q float64) {
l.mutex.Lock()
defer l.mutex.Unlock()
l.quota = q
} | go | func (l *rateLimiterImpl) setQuota(q float64) {
l.mutex.Lock()
defer l.mutex.Unlock()
l.quota = q
} | [
"func",
"(",
"l",
"*",
"rateLimiterImpl",
")",
"setQuota",
"(",
"q",
"float64",
")",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"quota",
"=",
"q",
"\n",
"}"
] | // Only used for testing. | [
"Only",
"used",
"for",
"testing",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L205-L209 | train |
dropbox/godropbox | rate_limiter/rate_limiter.go | Stop | func (l *rateLimiterImpl) Stop() {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.stopped {
return
}
l.stopped = true
close(l.stopChan)
l.ticker.Stop()
l.cond.Broadcast()
} | go | func (l *rateLimiterImpl) Stop() {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.stopped {
return
}
l.stopped = true
close(l.stopChan)
l.ticker.Stop()
l.cond.Broadcast()
} | [
"func",
"(",
"l",
"*",
"rateLimiterImpl",
")",
"Stop",
"(",
")",
"{",
"l",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"l",
".",
"stopped",
"{",
"return",
"\n",
"}",
"\n\n",
"l",
".",
"stopped",
"=",
"true",
"\n\n",
"close",
"(",
"l",
".",
"stopChan",
")",
"\n",
"l",
".",
"ticker",
".",
"Stop",
"(",
")",
"\n\n",
"l",
".",
"cond",
".",
"Broadcast",
"(",
")",
"\n",
"}"
] | // Stop the rate limiter. | [
"Stop",
"the",
"rate",
"limiter",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/rate_limiter/rate_limiter.go#L262-L276 | train |
dropbox/godropbox | io2/reader_to_writer_adapter.go | Write | func (sbself *splitBufferedWriter) Write(data []byte) (int, error) {
toCopy := len(sbself.userBuffer) - sbself.userBufferCount
if toCopy > len(data) {
toCopy = len(data)
}
copy(sbself.userBuffer[sbself.userBufferCount:sbself.userBufferCount+toCopy], data[:toCopy])
sbself.userBufferCount += toCopy
if toCopy < len(data) { // we need to overflow to remainder
count, err := sbself.remainder.Write(data[toCopy:])
return count + toCopy, err
}
return toCopy, nil
} | go | func (sbself *splitBufferedWriter) Write(data []byte) (int, error) {
toCopy := len(sbself.userBuffer) - sbself.userBufferCount
if toCopy > len(data) {
toCopy = len(data)
}
copy(sbself.userBuffer[sbself.userBufferCount:sbself.userBufferCount+toCopy], data[:toCopy])
sbself.userBufferCount += toCopy
if toCopy < len(data) { // we need to overflow to remainder
count, err := sbself.remainder.Write(data[toCopy:])
return count + toCopy, err
}
return toCopy, nil
} | [
"func",
"(",
"sbself",
"*",
"splitBufferedWriter",
")",
"Write",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"toCopy",
":=",
"len",
"(",
"sbself",
".",
"userBuffer",
")",
"-",
"sbself",
".",
"userBufferCount",
"\n",
"if",
"toCopy",
">",
"len",
"(",
"data",
")",
"{",
"toCopy",
"=",
"len",
"(",
"data",
")",
"\n",
"}",
"\n",
"copy",
"(",
"sbself",
".",
"userBuffer",
"[",
"sbself",
".",
"userBufferCount",
":",
"sbself",
".",
"userBufferCount",
"+",
"toCopy",
"]",
",",
"data",
"[",
":",
"toCopy",
"]",
")",
"\n",
"sbself",
".",
"userBufferCount",
"+=",
"toCopy",
"\n",
"if",
"toCopy",
"<",
"len",
"(",
"data",
")",
"{",
"// we need to overflow to remainder",
"count",
",",
"err",
":=",
"sbself",
".",
"remainder",
".",
"Write",
"(",
"data",
"[",
"toCopy",
":",
"]",
")",
"\n",
"return",
"count",
"+",
"toCopy",
",",
"err",
"\n",
"}",
"\n",
"return",
"toCopy",
",",
"nil",
"\n",
"}"
] | // writes, preferably to the userBuffer but then optionally to the remainder | [
"writes",
"preferably",
"to",
"the",
"userBuffer",
"but",
"then",
"optionally",
"to",
"the",
"remainder"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L67-L79 | train |
dropbox/godropbox | io2/reader_to_writer_adapter.go | RemoveUserBuffer | func (sbself *splitBufferedWriter) RemoveUserBuffer() (amountReturned int, err error) {
if len(sbself.userBuffer) > sbself.userBufferCount {
if len(sbself.remainder.Bytes()) != 0 {
err = errors.New("remainder must be clear if userBuffer isn't full")
panic(err)
}
}
amountReturned = sbself.userBufferCount
sbself.userBuffer = nil
sbself.userBufferCount = 0
return
} | go | func (sbself *splitBufferedWriter) RemoveUserBuffer() (amountReturned int, err error) {
if len(sbself.userBuffer) > sbself.userBufferCount {
if len(sbself.remainder.Bytes()) != 0 {
err = errors.New("remainder must be clear if userBuffer isn't full")
panic(err)
}
}
amountReturned = sbself.userBufferCount
sbself.userBuffer = nil
sbself.userBufferCount = 0
return
} | [
"func",
"(",
"sbself",
"*",
"splitBufferedWriter",
")",
"RemoveUserBuffer",
"(",
")",
"(",
"amountReturned",
"int",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"sbself",
".",
"userBuffer",
")",
">",
"sbself",
".",
"userBufferCount",
"{",
"if",
"len",
"(",
"sbself",
".",
"remainder",
".",
"Bytes",
"(",
")",
")",
"!=",
"0",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"amountReturned",
"=",
"sbself",
".",
"userBufferCount",
"\n",
"sbself",
".",
"userBuffer",
"=",
"nil",
"\n",
"sbself",
".",
"userBufferCount",
"=",
"0",
"\n",
"return",
"\n\n",
"}"
] | // removes the user buffer from the splitBufferedWriter
// This makes sure that if the user buffer is only somewhat full, no data remains in the remainder
// This preserves the remainder buffer, since that will be consumed later | [
"removes",
"the",
"user",
"buffer",
"from",
"the",
"splitBufferedWriter",
"This",
"makes",
"sure",
"that",
"if",
"the",
"user",
"buffer",
"is",
"only",
"somewhat",
"full",
"no",
"data",
"remains",
"in",
"the",
"remainder",
"This",
"preserves",
"the",
"remainder",
"buffer",
"since",
"that",
"will",
"be",
"consumed",
"later"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L88-L100 | train |
dropbox/godropbox | io2/reader_to_writer_adapter.go | InstallNewUserBufferAndResetRemainder | func (sbself *splitBufferedWriter) InstallNewUserBufferAndResetRemainder(
data []byte) {
sbself.remainder.Reset()
sbself.userBuffer = data
sbself.userBufferCount = 0
} | go | func (sbself *splitBufferedWriter) InstallNewUserBufferAndResetRemainder(
data []byte) {
sbself.remainder.Reset()
sbself.userBuffer = data
sbself.userBufferCount = 0
} | [
"func",
"(",
"sbself",
"*",
"splitBufferedWriter",
")",
"InstallNewUserBufferAndResetRemainder",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"sbself",
".",
"remainder",
".",
"Reset",
"(",
")",
"\n",
"sbself",
".",
"userBuffer",
"=",
"data",
"\n",
"sbself",
".",
"userBufferCount",
"=",
"0",
"\n",
"}"
] | // installs a user buffer into the splitBufferedWriter, resetting
// the remainder and original buffer | [
"installs",
"a",
"user",
"buffer",
"into",
"the",
"splitBufferedWriter",
"resetting",
"the",
"remainder",
"and",
"original",
"buffer"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L104-L110 | train |
dropbox/godropbox | io2/reader_to_writer_adapter.go | Read | func (rwaself *ReaderToWriterAdapter) Read(data []byte) (int, error) {
lenToCopy := len(rwaself.writeBuffer.Bytes()) - rwaself.offset
if lenToCopy > 0 {
// if we have leftover data from a previous call, we can return that only
if lenToCopy > len(data) {
lenToCopy = len(data)
}
copy(data[:lenToCopy],
rwaself.writeBuffer.Bytes()[rwaself.offset:rwaself.offset+lenToCopy])
rwaself.offset += lenToCopy
// only return deferred errors if we have consumed the entire remainder
if rwaself.offset < len(rwaself.writeBuffer.Bytes()) {
return lenToCopy, nil // if still remainder left, return nil
} else {
err := rwaself.deferredErr
rwaself.deferredErr = nil
return lenToCopy, err
}
}
rwaself.offset = 0
// if we have no data from previous runs, lets install the buffer and copy to the writer
rwaself.writeBuffer.InstallNewUserBufferAndResetRemainder(data)
for {
// read from the upstream
readBufferLenValid, err := rwaself.upstream.Read(rwaself.readBuffer)
var writeErr error
var closeErr error
if readBufferLenValid > 0 {
// copy data to the writer
_, writeErr = rwaself.writer.Write(rwaself.readBuffer[:readBufferLenValid])
}
if err == io.EOF && !rwaself.closedWriter {
rwaself.closedWriter = true
if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok {
closeErr = writeCloser.Close()
}
}
if err == nil && (writeErr != nil || closeErr != nil) {
_ = rwaself.drain() // if there was an error with the writer, drain the upstream
}
if (err == nil || err == io.EOF) && writeErr != nil {
err = writeErr
}
if (err == nil || err == io.EOF) && closeErr != nil {
err = closeErr
}
if rwaself.writeBuffer.GetAmountCopiedToUser() > 0 || err != nil {
if rwaself.offset < len(rwaself.writeBuffer.Bytes()) {
rwaself.deferredErr = err
err = nil
}
amountCopiedToUser, err2 := rwaself.writeBuffer.RemoveUserBuffer()
if err == nil && err2 != nil {
err = err2 // this is an internal assertion/check. it should not trip
} // possibly change to a panic?
return amountCopiedToUser, err
}
}
} | go | func (rwaself *ReaderToWriterAdapter) Read(data []byte) (int, error) {
lenToCopy := len(rwaself.writeBuffer.Bytes()) - rwaself.offset
if lenToCopy > 0 {
// if we have leftover data from a previous call, we can return that only
if lenToCopy > len(data) {
lenToCopy = len(data)
}
copy(data[:lenToCopy],
rwaself.writeBuffer.Bytes()[rwaself.offset:rwaself.offset+lenToCopy])
rwaself.offset += lenToCopy
// only return deferred errors if we have consumed the entire remainder
if rwaself.offset < len(rwaself.writeBuffer.Bytes()) {
return lenToCopy, nil // if still remainder left, return nil
} else {
err := rwaself.deferredErr
rwaself.deferredErr = nil
return lenToCopy, err
}
}
rwaself.offset = 0
// if we have no data from previous runs, lets install the buffer and copy to the writer
rwaself.writeBuffer.InstallNewUserBufferAndResetRemainder(data)
for {
// read from the upstream
readBufferLenValid, err := rwaself.upstream.Read(rwaself.readBuffer)
var writeErr error
var closeErr error
if readBufferLenValid > 0 {
// copy data to the writer
_, writeErr = rwaself.writer.Write(rwaself.readBuffer[:readBufferLenValid])
}
if err == io.EOF && !rwaself.closedWriter {
rwaself.closedWriter = true
if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok {
closeErr = writeCloser.Close()
}
}
if err == nil && (writeErr != nil || closeErr != nil) {
_ = rwaself.drain() // if there was an error with the writer, drain the upstream
}
if (err == nil || err == io.EOF) && writeErr != nil {
err = writeErr
}
if (err == nil || err == io.EOF) && closeErr != nil {
err = closeErr
}
if rwaself.writeBuffer.GetAmountCopiedToUser() > 0 || err != nil {
if rwaself.offset < len(rwaself.writeBuffer.Bytes()) {
rwaself.deferredErr = err
err = nil
}
amountCopiedToUser, err2 := rwaself.writeBuffer.RemoveUserBuffer()
if err == nil && err2 != nil {
err = err2 // this is an internal assertion/check. it should not trip
} // possibly change to a panic?
return amountCopiedToUser, err
}
}
} | [
"func",
"(",
"rwaself",
"*",
"ReaderToWriterAdapter",
")",
"Read",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"lenToCopy",
":=",
"len",
"(",
"rwaself",
".",
"writeBuffer",
".",
"Bytes",
"(",
")",
")",
"-",
"rwaself",
".",
"offset",
"\n",
"if",
"lenToCopy",
">",
"0",
"{",
"// if we have leftover data from a previous call, we can return that only",
"if",
"lenToCopy",
">",
"len",
"(",
"data",
")",
"{",
"lenToCopy",
"=",
"len",
"(",
"data",
")",
"\n",
"}",
"\n",
"copy",
"(",
"data",
"[",
":",
"lenToCopy",
"]",
",",
"rwaself",
".",
"writeBuffer",
".",
"Bytes",
"(",
")",
"[",
"rwaself",
".",
"offset",
":",
"rwaself",
".",
"offset",
"+",
"lenToCopy",
"]",
")",
"\n\n",
"rwaself",
".",
"offset",
"+=",
"lenToCopy",
"\n\n",
"// only return deferred errors if we have consumed the entire remainder",
"if",
"rwaself",
".",
"offset",
"<",
"len",
"(",
"rwaself",
".",
"writeBuffer",
".",
"Bytes",
"(",
")",
")",
"{",
"return",
"lenToCopy",
",",
"nil",
"// if still remainder left, return nil",
"\n",
"}",
"else",
"{",
"err",
":=",
"rwaself",
".",
"deferredErr",
"\n",
"rwaself",
".",
"deferredErr",
"=",
"nil",
"\n",
"return",
"lenToCopy",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"rwaself",
".",
"offset",
"=",
"0",
"\n",
"// if we have no data from previous runs, lets install the buffer and copy to the writer",
"rwaself",
".",
"writeBuffer",
".",
"InstallNewUserBufferAndResetRemainder",
"(",
"data",
")",
"\n",
"for",
"{",
"// read from the upstream",
"readBufferLenValid",
",",
"err",
":=",
"rwaself",
".",
"upstream",
".",
"Read",
"(",
"rwaself",
".",
"readBuffer",
")",
"\n",
"var",
"writeErr",
"error",
"\n",
"var",
"closeErr",
"error",
"\n",
"if",
"readBufferLenValid",
">",
"0",
"{",
"// copy data to the writer",
"_",
",",
"writeErr",
"=",
"rwaself",
".",
"writer",
".",
"Write",
"(",
"rwaself",
".",
"readBuffer",
"[",
":",
"readBufferLenValid",
"]",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"&&",
"!",
"rwaself",
".",
"closedWriter",
"{",
"rwaself",
".",
"closedWriter",
"=",
"true",
"\n",
"if",
"writeCloser",
",",
"ok",
":=",
"rwaself",
".",
"writer",
".",
"(",
"io",
".",
"WriteCloser",
")",
";",
"ok",
"{",
"closeErr",
"=",
"writeCloser",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"(",
"writeErr",
"!=",
"nil",
"||",
"closeErr",
"!=",
"nil",
")",
"{",
"_",
"=",
"rwaself",
".",
"drain",
"(",
")",
"// if there was an error with the writer, drain the upstream",
"\n",
"}",
"\n",
"if",
"(",
"err",
"==",
"nil",
"||",
"err",
"==",
"io",
".",
"EOF",
")",
"&&",
"writeErr",
"!=",
"nil",
"{",
"err",
"=",
"writeErr",
"\n",
"}",
"\n",
"if",
"(",
"err",
"==",
"nil",
"||",
"err",
"==",
"io",
".",
"EOF",
")",
"&&",
"closeErr",
"!=",
"nil",
"{",
"err",
"=",
"closeErr",
"\n",
"}",
"\n",
"if",
"rwaself",
".",
"writeBuffer",
".",
"GetAmountCopiedToUser",
"(",
")",
">",
"0",
"||",
"err",
"!=",
"nil",
"{",
"if",
"rwaself",
".",
"offset",
"<",
"len",
"(",
"rwaself",
".",
"writeBuffer",
".",
"Bytes",
"(",
")",
")",
"{",
"rwaself",
".",
"deferredErr",
"=",
"err",
"\n",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"amountCopiedToUser",
",",
"err2",
":=",
"rwaself",
".",
"writeBuffer",
".",
"RemoveUserBuffer",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"err2",
"!=",
"nil",
"{",
"err",
"=",
"err2",
"// this is an internal assertion/check. it should not trip",
"\n",
"}",
"// possibly change to a panic?",
"\n",
"return",
"amountCopiedToUser",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // implements the Read interface by wrapping the Writer with some buffers | [
"implements",
"the",
"Read",
"interface",
"by",
"wrapping",
"the",
"Writer",
"with",
"some",
"buffers"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L117-L177 | train |
dropbox/godropbox | io2/reader_to_writer_adapter.go | Close | func (rwaself *ReaderToWriterAdapter) Close() error {
var wCloseErr error
var rCloseErr error
if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok {
if !rwaself.closedWriter {
wCloseErr = writeCloser.Close()
}
}
if readCloser, ok := rwaself.upstream.(io.ReadCloser); ok {
rCloseErr = readCloser.Close()
} else {
rCloseErr = rwaself.drain()
}
if rCloseErr != nil && rCloseErr != io.EOF {
return rCloseErr
}
if wCloseErr != nil && wCloseErr != io.EOF {
return wCloseErr
}
return nil
} | go | func (rwaself *ReaderToWriterAdapter) Close() error {
var wCloseErr error
var rCloseErr error
if writeCloser, ok := rwaself.writer.(io.WriteCloser); ok {
if !rwaself.closedWriter {
wCloseErr = writeCloser.Close()
}
}
if readCloser, ok := rwaself.upstream.(io.ReadCloser); ok {
rCloseErr = readCloser.Close()
} else {
rCloseErr = rwaself.drain()
}
if rCloseErr != nil && rCloseErr != io.EOF {
return rCloseErr
}
if wCloseErr != nil && wCloseErr != io.EOF {
return wCloseErr
}
return nil
} | [
"func",
"(",
"rwaself",
"*",
"ReaderToWriterAdapter",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"wCloseErr",
"error",
"\n",
"var",
"rCloseErr",
"error",
"\n",
"if",
"writeCloser",
",",
"ok",
":=",
"rwaself",
".",
"writer",
".",
"(",
"io",
".",
"WriteCloser",
")",
";",
"ok",
"{",
"if",
"!",
"rwaself",
".",
"closedWriter",
"{",
"wCloseErr",
"=",
"writeCloser",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"readCloser",
",",
"ok",
":=",
"rwaself",
".",
"upstream",
".",
"(",
"io",
".",
"ReadCloser",
")",
";",
"ok",
"{",
"rCloseErr",
"=",
"readCloser",
".",
"Close",
"(",
")",
"\n",
"}",
"else",
"{",
"rCloseErr",
"=",
"rwaself",
".",
"drain",
"(",
")",
"\n",
"}",
"\n",
"if",
"rCloseErr",
"!=",
"nil",
"&&",
"rCloseErr",
"!=",
"io",
".",
"EOF",
"{",
"return",
"rCloseErr",
"\n",
"}",
"\n",
"if",
"wCloseErr",
"!=",
"nil",
"&&",
"wCloseErr",
"!=",
"io",
".",
"EOF",
"{",
"return",
"wCloseErr",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // interrupt the read by closing all resources | [
"interrupt",
"the",
"read",
"by",
"closing",
"all",
"resources"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/io2/reader_to_writer_adapter.go#L180-L200 | train |
dropbox/godropbox | net2/http2/gzip.go | NewGzipResponseWriter | func NewGzipResponseWriter(writer http.ResponseWriter, compressionLevel int) gzipResponseWriter {
gzWriter, _ := gzip.NewWriterLevel(writer, compressionLevel)
return gzipResponseWriter{ResponseWriter: writer, gzWriter: gzWriter}
} | go | func NewGzipResponseWriter(writer http.ResponseWriter, compressionLevel int) gzipResponseWriter {
gzWriter, _ := gzip.NewWriterLevel(writer, compressionLevel)
return gzipResponseWriter{ResponseWriter: writer, gzWriter: gzWriter}
} | [
"func",
"NewGzipResponseWriter",
"(",
"writer",
"http",
".",
"ResponseWriter",
",",
"compressionLevel",
"int",
")",
"gzipResponseWriter",
"{",
"gzWriter",
",",
"_",
":=",
"gzip",
".",
"NewWriterLevel",
"(",
"writer",
",",
"compressionLevel",
")",
"\n",
"return",
"gzipResponseWriter",
"{",
"ResponseWriter",
":",
"writer",
",",
"gzWriter",
":",
"gzWriter",
"}",
"\n",
"}"
] | // compressionLevel - one of the compression levels in the gzip package. | [
"compressionLevel",
"-",
"one",
"of",
"the",
"compression",
"levels",
"in",
"the",
"gzip",
"package",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/gzip.go#L19-L22 | train |
dropbox/godropbox | sys/filelock/filelock.go | TryRLock | func (f *FileLock) TryRLock() error {
return f.performLock(syscall.LOCK_SH | syscall.LOCK_NB)
} | go | func (f *FileLock) TryRLock() error {
return f.performLock(syscall.LOCK_SH | syscall.LOCK_NB)
} | [
"func",
"(",
"f",
"*",
"FileLock",
")",
"TryRLock",
"(",
")",
"error",
"{",
"return",
"f",
".",
"performLock",
"(",
"syscall",
".",
"LOCK_SH",
"|",
"syscall",
".",
"LOCK_NB",
")",
"\n",
"}"
] | // Non blocking way to try to acquire a shared lock. | [
"Non",
"blocking",
"way",
"to",
"try",
"to",
"acquire",
"a",
"shared",
"lock",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sys/filelock/filelock.go#L70-L72 | train |
dropbox/godropbox | sys/filelock/filelock.go | TryLock | func (f *FileLock) TryLock() error {
return f.performLock(syscall.LOCK_EX | syscall.LOCK_NB)
} | go | func (f *FileLock) TryLock() error {
return f.performLock(syscall.LOCK_EX | syscall.LOCK_NB)
} | [
"func",
"(",
"f",
"*",
"FileLock",
")",
"TryLock",
"(",
")",
"error",
"{",
"return",
"f",
".",
"performLock",
"(",
"syscall",
".",
"LOCK_EX",
"|",
"syscall",
".",
"LOCK_NB",
")",
"\n",
"}"
] | // Non blocking way to try to acquire an exclusive lock. | [
"Non",
"blocking",
"way",
"to",
"try",
"to",
"acquire",
"an",
"exclusive",
"lock",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sys/filelock/filelock.go#L80-L82 | train |
dropbox/godropbox | database/sqlbuilder/column.go | DateTimeColumn | func DateTimeColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in datetime column")
}
dc := &dateTimeColumn{}
dc.name = name
dc.nullable = nullable
return dc
} | go | func DateTimeColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in datetime column")
}
dc := &dateTimeColumn{}
dc.name = name
dc.nullable = nullable
return dc
} | [
"func",
"DateTimeColumn",
"(",
"name",
"string",
",",
"nullable",
"NullableColumn",
")",
"NonAliasColumn",
"{",
"if",
"!",
"validIdentifierName",
"(",
"name",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"dc",
":=",
"&",
"dateTimeColumn",
"{",
"}",
"\n",
"dc",
".",
"name",
"=",
"name",
"\n",
"dc",
".",
"nullable",
"=",
"nullable",
"\n",
"return",
"dc",
"\n",
"}"
] | // Representation of DateTime columns
// This function will panic if name is not valid | [
"Representation",
"of",
"DateTime",
"columns",
"This",
"function",
"will",
"panic",
"if",
"name",
"is",
"not",
"valid"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L140-L148 | train |
dropbox/godropbox | database/sqlbuilder/column.go | IntColumn | func IntColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in int column")
}
ic := &integerColumn{}
ic.name = name
ic.nullable = nullable
return ic
} | go | func IntColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in int column")
}
ic := &integerColumn{}
ic.name = name
ic.nullable = nullable
return ic
} | [
"func",
"IntColumn",
"(",
"name",
"string",
",",
"nullable",
"NullableColumn",
")",
"NonAliasColumn",
"{",
"if",
"!",
"validIdentifierName",
"(",
"name",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ic",
":=",
"&",
"integerColumn",
"{",
"}",
"\n",
"ic",
".",
"name",
"=",
"name",
"\n",
"ic",
".",
"nullable",
"=",
"nullable",
"\n",
"return",
"ic",
"\n",
"}"
] | // Representation of any integer column
// This function will panic if name is not valid | [
"Representation",
"of",
"any",
"integer",
"column",
"This",
"function",
"will",
"panic",
"if",
"name",
"is",
"not",
"valid"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L157-L165 | train |
dropbox/godropbox | database/sqlbuilder/column.go | DoubleColumn | func DoubleColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in int column")
}
ic := &doubleColumn{}
ic.name = name
ic.nullable = nullable
return ic
} | go | func DoubleColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in int column")
}
ic := &doubleColumn{}
ic.name = name
ic.nullable = nullable
return ic
} | [
"func",
"DoubleColumn",
"(",
"name",
"string",
",",
"nullable",
"NullableColumn",
")",
"NonAliasColumn",
"{",
"if",
"!",
"validIdentifierName",
"(",
"name",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ic",
":=",
"&",
"doubleColumn",
"{",
"}",
"\n",
"ic",
".",
"name",
"=",
"name",
"\n",
"ic",
".",
"nullable",
"=",
"nullable",
"\n",
"return",
"ic",
"\n",
"}"
] | // Representation of any double column
// This function will panic if name is not valid | [
"Representation",
"of",
"any",
"double",
"column",
"This",
"function",
"will",
"panic",
"if",
"name",
"is",
"not",
"valid"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L174-L182 | train |
dropbox/godropbox | database/sqlbuilder/column.go | BoolColumn | func BoolColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in bool column")
}
bc := &booleanColumn{}
bc.name = name
bc.nullable = nullable
return bc
} | go | func BoolColumn(name string, nullable NullableColumn) NonAliasColumn {
if !validIdentifierName(name) {
panic("Invalid column name in bool column")
}
bc := &booleanColumn{}
bc.name = name
bc.nullable = nullable
return bc
} | [
"func",
"BoolColumn",
"(",
"name",
"string",
",",
"nullable",
"NullableColumn",
")",
"NonAliasColumn",
"{",
"if",
"!",
"validIdentifierName",
"(",
"name",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"bc",
":=",
"&",
"booleanColumn",
"{",
"}",
"\n",
"bc",
".",
"name",
"=",
"name",
"\n",
"bc",
".",
"nullable",
"=",
"nullable",
"\n",
"return",
"bc",
"\n",
"}"
] | // Representation of TINYINT used as a bool
// This function will panic if name is not valid | [
"Representation",
"of",
"TINYINT",
"used",
"as",
"a",
"bool",
"This",
"function",
"will",
"panic",
"if",
"name",
"is",
"not",
"valid"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/column.go#L194-L202 | train |
dropbox/godropbox | resource_pool/managed_handle.go | NewManagedHandle | func NewManagedHandle(
resourceLocation string,
handle interface{},
pool ResourcePool,
options Options) ManagedHandle {
h := &managedHandleImpl{
location: resourceLocation,
handle: handle,
pool: pool,
options: options,
}
atomic.StoreInt32(&h.isActive, 1)
return h
} | go | func NewManagedHandle(
resourceLocation string,
handle interface{},
pool ResourcePool,
options Options) ManagedHandle {
h := &managedHandleImpl{
location: resourceLocation,
handle: handle,
pool: pool,
options: options,
}
atomic.StoreInt32(&h.isActive, 1)
return h
} | [
"func",
"NewManagedHandle",
"(",
"resourceLocation",
"string",
",",
"handle",
"interface",
"{",
"}",
",",
"pool",
"ResourcePool",
",",
"options",
"Options",
")",
"ManagedHandle",
"{",
"h",
":=",
"&",
"managedHandleImpl",
"{",
"location",
":",
"resourceLocation",
",",
"handle",
":",
"handle",
",",
"pool",
":",
"pool",
",",
"options",
":",
"options",
",",
"}",
"\n",
"atomic",
".",
"StoreInt32",
"(",
"&",
"h",
".",
"isActive",
",",
"1",
")",
"\n\n",
"return",
"h",
"\n",
"}"
] | // This creates a managed handle wrapper. | [
"This",
"creates",
"a",
"managed",
"handle",
"wrapper",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/managed_handle.go#L46-L61 | train |
dropbox/godropbox | memcache/static_shard_manager.go | NewStaticShardManager | func NewStaticShardManager(
serverAddrs []string,
shardFunc func(key string, numShard int) (shard int),
options net2.ConnectionOptions) ShardManager {
manager := &StaticShardManager{}
manager.Init(
shardFunc,
func(err error) { log.Print(err) },
log.Print,
options)
shardStates := make([]ShardState, len(serverAddrs), len(serverAddrs))
for i, addr := range serverAddrs {
shardStates[i].Address = addr
shardStates[i].State = ActiveServer
}
manager.UpdateShardStates(shardStates)
return manager
} | go | func NewStaticShardManager(
serverAddrs []string,
shardFunc func(key string, numShard int) (shard int),
options net2.ConnectionOptions) ShardManager {
manager := &StaticShardManager{}
manager.Init(
shardFunc,
func(err error) { log.Print(err) },
log.Print,
options)
shardStates := make([]ShardState, len(serverAddrs), len(serverAddrs))
for i, addr := range serverAddrs {
shardStates[i].Address = addr
shardStates[i].State = ActiveServer
}
manager.UpdateShardStates(shardStates)
return manager
} | [
"func",
"NewStaticShardManager",
"(",
"serverAddrs",
"[",
"]",
"string",
",",
"shardFunc",
"func",
"(",
"key",
"string",
",",
"numShard",
"int",
")",
"(",
"shard",
"int",
")",
",",
"options",
"net2",
".",
"ConnectionOptions",
")",
"ShardManager",
"{",
"manager",
":=",
"&",
"StaticShardManager",
"{",
"}",
"\n",
"manager",
".",
"Init",
"(",
"shardFunc",
",",
"func",
"(",
"err",
"error",
")",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"}",
",",
"log",
".",
"Print",
",",
"options",
")",
"\n\n",
"shardStates",
":=",
"make",
"(",
"[",
"]",
"ShardState",
",",
"len",
"(",
"serverAddrs",
")",
",",
"len",
"(",
"serverAddrs",
")",
")",
"\n",
"for",
"i",
",",
"addr",
":=",
"range",
"serverAddrs",
"{",
"shardStates",
"[",
"i",
"]",
".",
"Address",
"=",
"addr",
"\n",
"shardStates",
"[",
"i",
"]",
".",
"State",
"=",
"ActiveServer",
"\n",
"}",
"\n\n",
"manager",
".",
"UpdateShardStates",
"(",
"shardStates",
")",
"\n\n",
"return",
"manager",
"\n",
"}"
] | // This creates a StaticShardManager, which returns connections from a static
// list of memcache shards. | [
"This",
"creates",
"a",
"StaticShardManager",
"which",
"returns",
"connections",
"from",
"a",
"static",
"list",
"of",
"memcache",
"shards",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/static_shard_manager.go#L22-L43 | train |
dropbox/godropbox | bufio2/look_ahead_buffer.go | NewLookAheadBuffer | func NewLookAheadBuffer(src io.Reader, bufferSize int) *LookAheadBuffer {
return NewLookAheadBufferUsing(src, make([]byte, bufferSize, bufferSize))
} | go | func NewLookAheadBuffer(src io.Reader, bufferSize int) *LookAheadBuffer {
return NewLookAheadBufferUsing(src, make([]byte, bufferSize, bufferSize))
} | [
"func",
"NewLookAheadBuffer",
"(",
"src",
"io",
".",
"Reader",
",",
"bufferSize",
"int",
")",
"*",
"LookAheadBuffer",
"{",
"return",
"NewLookAheadBufferUsing",
"(",
"src",
",",
"make",
"(",
"[",
"]",
"byte",
",",
"bufferSize",
",",
"bufferSize",
")",
")",
"\n",
"}"
] | // NewLookAheadBuffer returns a new LookAheadBuffer whose raw buffer has EXACTLY
// the specified size. | [
"NewLookAheadBuffer",
"returns",
"a",
"new",
"LookAheadBuffer",
"whose",
"raw",
"buffer",
"has",
"EXACTLY",
"the",
"specified",
"size",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/bufio2/look_ahead_buffer.go#L24-L26 | train |
dropbox/godropbox | bufio2/look_ahead_buffer.go | NewLookAheadBufferUsing | func NewLookAheadBufferUsing(src io.Reader, rawBuffer []byte) *LookAheadBuffer {
return &LookAheadBuffer{
src: src,
buffer: rawBuffer,
bytesBuffered: 0,
}
} | go | func NewLookAheadBufferUsing(src io.Reader, rawBuffer []byte) *LookAheadBuffer {
return &LookAheadBuffer{
src: src,
buffer: rawBuffer,
bytesBuffered: 0,
}
} | [
"func",
"NewLookAheadBufferUsing",
"(",
"src",
"io",
".",
"Reader",
",",
"rawBuffer",
"[",
"]",
"byte",
")",
"*",
"LookAheadBuffer",
"{",
"return",
"&",
"LookAheadBuffer",
"{",
"src",
":",
"src",
",",
"buffer",
":",
"rawBuffer",
",",
"bytesBuffered",
":",
"0",
",",
"}",
"\n",
"}"
] | // NewLookAheadBufferUsing returns a new LookAheadBuffer which uses the
// provided buffer as its raw buffer. This allows buffer reuse, which reduces
// unnecessary memory allocation. | [
"NewLookAheadBufferUsing",
"returns",
"a",
"new",
"LookAheadBuffer",
"which",
"uses",
"the",
"provided",
"buffer",
"as",
"its",
"raw",
"buffer",
".",
"This",
"allows",
"buffer",
"reuse",
"which",
"reduces",
"unnecessary",
"memory",
"allocation",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/bufio2/look_ahead_buffer.go#L31-L37 | train |
dropbox/godropbox | bufio2/look_ahead_buffer.go | ConsumeAll | func (b *LookAheadBuffer) ConsumeAll() {
err := b.Consume(b.bytesBuffered)
if err != nil { // This should never happen
panic(err)
}
} | go | func (b *LookAheadBuffer) ConsumeAll() {
err := b.Consume(b.bytesBuffered)
if err != nil { // This should never happen
panic(err)
}
} | [
"func",
"(",
"b",
"*",
"LookAheadBuffer",
")",
"ConsumeAll",
"(",
")",
"{",
"err",
":=",
"b",
".",
"Consume",
"(",
"b",
".",
"bytesBuffered",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// This should never happen",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // ConsumeAll drops all populated bytes from the look ahead buffer. | [
"ConsumeAll",
"drops",
"all",
"populated",
"bytes",
"from",
"the",
"look",
"ahead",
"buffer",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/bufio2/look_ahead_buffer.go#L126-L131 | train |
dropbox/godropbox | database/binlog/query_event.go | IsModeEnabled | func (e *QueryEvent) IsModeEnabled(mode mysql_proto.SqlMode_BitPosition) bool {
if e.sqlMode == nil {
return false
}
return (*e.sqlMode & (uint64(1) << uint(mode))) != 0
} | go | func (e *QueryEvent) IsModeEnabled(mode mysql_proto.SqlMode_BitPosition) bool {
if e.sqlMode == nil {
return false
}
return (*e.sqlMode & (uint64(1) << uint(mode))) != 0
} | [
"func",
"(",
"e",
"*",
"QueryEvent",
")",
"IsModeEnabled",
"(",
"mode",
"mysql_proto",
".",
"SqlMode_BitPosition",
")",
"bool",
"{",
"if",
"e",
".",
"sqlMode",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"(",
"*",
"e",
".",
"sqlMode",
"&",
"(",
"uint64",
"(",
"1",
")",
"<<",
"uint",
"(",
"mode",
")",
")",
")",
"!=",
"0",
"\n",
"}"
] | // IsModeEnabled returns true iff sql mode status is set and the mode bit is
// set. | [
"IsModeEnabled",
"returns",
"true",
"iff",
"sql",
"mode",
"status",
"is",
"set",
"and",
"the",
"mode",
"bit",
"is",
"set",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/query_event.go#L152-L158 | train |
dropbox/godropbox | database/binlog/query_event.go | Parse | func (p *QueryEventParser) Parse(raw *RawV4Event) (Event, error) {
query := &QueryEvent{
Event: raw,
}
type fixedBodyStruct struct {
ThreadId uint32
Duration uint32
DatabaseNameLength uint8
ErrorCode uint16
StatusLength uint16
}
fixed := fixedBodyStruct{}
_, err := readLittleEndian(raw.FixedLengthData(), &fixed)
if err != nil {
return raw, errors.Wrap(err, "Failed to read fixed body")
}
query.threadId = fixed.ThreadId
query.duration = fixed.Duration
query.errorCode = mysql_proto.ErrorCode_Type(fixed.ErrorCode)
data := raw.VariableLengthData()
dbNameEnd := int(fixed.StatusLength) + int(fixed.DatabaseNameLength)
if dbNameEnd+1 > len(data) {
return raw, errors.Newf("Invalid message length")
}
query.statusBytes = data[:fixed.StatusLength]
query.databaseName = data[fixed.StatusLength:dbNameEnd]
query.query = data[dbNameEnd+1:]
err = p.parseStatus(query)
if err != nil {
return raw, err
}
return query, nil
} | go | func (p *QueryEventParser) Parse(raw *RawV4Event) (Event, error) {
query := &QueryEvent{
Event: raw,
}
type fixedBodyStruct struct {
ThreadId uint32
Duration uint32
DatabaseNameLength uint8
ErrorCode uint16
StatusLength uint16
}
fixed := fixedBodyStruct{}
_, err := readLittleEndian(raw.FixedLengthData(), &fixed)
if err != nil {
return raw, errors.Wrap(err, "Failed to read fixed body")
}
query.threadId = fixed.ThreadId
query.duration = fixed.Duration
query.errorCode = mysql_proto.ErrorCode_Type(fixed.ErrorCode)
data := raw.VariableLengthData()
dbNameEnd := int(fixed.StatusLength) + int(fixed.DatabaseNameLength)
if dbNameEnd+1 > len(data) {
return raw, errors.Newf("Invalid message length")
}
query.statusBytes = data[:fixed.StatusLength]
query.databaseName = data[fixed.StatusLength:dbNameEnd]
query.query = data[dbNameEnd+1:]
err = p.parseStatus(query)
if err != nil {
return raw, err
}
return query, nil
} | [
"func",
"(",
"p",
"*",
"QueryEventParser",
")",
"Parse",
"(",
"raw",
"*",
"RawV4Event",
")",
"(",
"Event",
",",
"error",
")",
"{",
"query",
":=",
"&",
"QueryEvent",
"{",
"Event",
":",
"raw",
",",
"}",
"\n\n",
"type",
"fixedBodyStruct",
"struct",
"{",
"ThreadId",
"uint32",
"\n",
"Duration",
"uint32",
"\n",
"DatabaseNameLength",
"uint8",
"\n",
"ErrorCode",
"uint16",
"\n",
"StatusLength",
"uint16",
"\n",
"}",
"\n\n",
"fixed",
":=",
"fixedBodyStruct",
"{",
"}",
"\n\n",
"_",
",",
"err",
":=",
"readLittleEndian",
"(",
"raw",
".",
"FixedLengthData",
"(",
")",
",",
"&",
"fixed",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"query",
".",
"threadId",
"=",
"fixed",
".",
"ThreadId",
"\n",
"query",
".",
"duration",
"=",
"fixed",
".",
"Duration",
"\n",
"query",
".",
"errorCode",
"=",
"mysql_proto",
".",
"ErrorCode_Type",
"(",
"fixed",
".",
"ErrorCode",
")",
"\n\n",
"data",
":=",
"raw",
".",
"VariableLengthData",
"(",
")",
"\n\n",
"dbNameEnd",
":=",
"int",
"(",
"fixed",
".",
"StatusLength",
")",
"+",
"int",
"(",
"fixed",
".",
"DatabaseNameLength",
")",
"\n",
"if",
"dbNameEnd",
"+",
"1",
">",
"len",
"(",
"data",
")",
"{",
"return",
"raw",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"query",
".",
"statusBytes",
"=",
"data",
"[",
":",
"fixed",
".",
"StatusLength",
"]",
"\n\n",
"query",
".",
"databaseName",
"=",
"data",
"[",
"fixed",
".",
"StatusLength",
":",
"dbNameEnd",
"]",
"\n\n",
"query",
".",
"query",
"=",
"data",
"[",
"dbNameEnd",
"+",
"1",
":",
"]",
"\n\n",
"err",
"=",
"p",
".",
"parseStatus",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"query",
",",
"nil",
"\n",
"}"
] | // QueryEventParser's Parse processes a raw query event into a QueryEvent. | [
"QueryEventParser",
"s",
"Parse",
"processes",
"a",
"raw",
"query",
"event",
"into",
"a",
"QueryEvent",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/query_event.go#L259-L302 | train |
dropbox/godropbox | database/binlog/rotate_event.go | Parse | func (p *RotateEventParser) Parse(raw *RawV4Event) (Event, error) {
rotate := &RotateEvent{
Event: raw,
newLogName: raw.VariableLengthData(),
}
_, err := readLittleEndian(raw.FixedLengthData(), &rotate.newPosition)
if err != nil {
return raw, errors.Wrap(err, "Failed to read new log position")
}
return rotate, nil
} | go | func (p *RotateEventParser) Parse(raw *RawV4Event) (Event, error) {
rotate := &RotateEvent{
Event: raw,
newLogName: raw.VariableLengthData(),
}
_, err := readLittleEndian(raw.FixedLengthData(), &rotate.newPosition)
if err != nil {
return raw, errors.Wrap(err, "Failed to read new log position")
}
return rotate, nil
} | [
"func",
"(",
"p",
"*",
"RotateEventParser",
")",
"Parse",
"(",
"raw",
"*",
"RawV4Event",
")",
"(",
"Event",
",",
"error",
")",
"{",
"rotate",
":=",
"&",
"RotateEvent",
"{",
"Event",
":",
"raw",
",",
"newLogName",
":",
"raw",
".",
"VariableLengthData",
"(",
")",
",",
"}",
"\n\n",
"_",
",",
"err",
":=",
"readLittleEndian",
"(",
"raw",
".",
"FixedLengthData",
"(",
")",
",",
"&",
"rotate",
".",
"newPosition",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"rotate",
",",
"nil",
"\n",
"}"
] | // RotateEventParser's Parse processes a raw rotate event into a RotateEvent. | [
"RotateEventParser",
"s",
"Parse",
"processes",
"a",
"raw",
"rotate",
"event",
"into",
"a",
"RotateEvent",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/rotate_event.go#L57-L69 | train |
dropbox/godropbox | database/binlog/format_description_event.go | FixedLengthDataSizeForType | func (e *FormatDescriptionEvent) FixedLengthDataSizeForType(
eventType mysql_proto.LogEventType_Type) int {
return e.fixedLengthSizes[eventType]
} | go | func (e *FormatDescriptionEvent) FixedLengthDataSizeForType(
eventType mysql_proto.LogEventType_Type) int {
return e.fixedLengthSizes[eventType]
} | [
"func",
"(",
"e",
"*",
"FormatDescriptionEvent",
")",
"FixedLengthDataSizeForType",
"(",
"eventType",
"mysql_proto",
".",
"LogEventType_Type",
")",
"int",
"{",
"return",
"e",
".",
"fixedLengthSizes",
"[",
"eventType",
"]",
"\n",
"}"
] | // FixedLengthDataSizeForType returns the size of fixed length data for each
// event type. | [
"FixedLengthDataSizeForType",
"returns",
"the",
"size",
"of",
"fixed",
"length",
"data",
"for",
"each",
"event",
"type",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/format_description_event.go#L73-L77 | train |
dropbox/godropbox | database/binlog/format_description_event.go | Parse | func (p *FormatDescriptionEventParser) Parse(raw *RawV4Event) (Event, error) {
fde := &FormatDescriptionEvent{
Event: raw,
fixedLengthSizes: make(map[mysql_proto.LogEventType_Type]int),
}
data := raw.VariableLengthData()
data, err := readLittleEndian(data, &fde.binlogVersion)
if err != nil {
return raw, errors.Wrap(err, "Failed to read binlog version")
}
serverVersion, data, err := readSlice(data, 50)
if err != nil {
return raw, errors.Wrap(err, "Failed to read server version")
}
if idx := bytes.IndexByte(serverVersion, byte(0)); idx > -1 {
serverVersion = serverVersion[:idx]
}
fde.serverVersion = serverVersion
data, err = readLittleEndian(data, &fde.createdTimestamp)
if err != nil {
return raw, errors.Wrap(err, "Failed to read created timestamp")
}
var totalHeaderSize uint8
data, err = readLittleEndian(data, &totalHeaderSize)
if err != nil {
return raw, errors.Wrap(err, "Failed to read total header size")
}
fde.extraHeadersSize = int(totalHeaderSize) - sizeOfBasicV4EventHeader
numEvents := len(mysql_proto.LogEventType_Type_value)
hasChecksum := true
if len(data) == 27 { // mysql 5.5(.37)
numEvents = 28
hasChecksum = false
} else if len(data) == 40 { // mysql 5.6(.17)
// This is a relay log where the master is 5.5 and slave is 5.6
if data[int(mysql_proto.LogEventType_WRITE_ROWS_EVENT)-1] == 0 {
numEvents = 28
}
} else {
return raw, errors.Newf(
"Unable to parse FDE for mysql variant: %s",
fde.serverVersion)
}
// unknown event's fixed length is implicit.
fde.fixedLengthSizes[mysql_proto.LogEventType_UNKNOWN_EVENT] = 0
for i := 1; i < numEvents; i++ {
fde.fixedLengthSizes[mysql_proto.LogEventType_Type(i)] = int(data[i-1])
}
if hasChecksum {
fde.checksumAlgorithm = mysql_proto.ChecksumAlgorithm_Type(
data[len(data)-5])
raw.SetChecksumSize(4)
}
return fde, nil
} | go | func (p *FormatDescriptionEventParser) Parse(raw *RawV4Event) (Event, error) {
fde := &FormatDescriptionEvent{
Event: raw,
fixedLengthSizes: make(map[mysql_proto.LogEventType_Type]int),
}
data := raw.VariableLengthData()
data, err := readLittleEndian(data, &fde.binlogVersion)
if err != nil {
return raw, errors.Wrap(err, "Failed to read binlog version")
}
serverVersion, data, err := readSlice(data, 50)
if err != nil {
return raw, errors.Wrap(err, "Failed to read server version")
}
if idx := bytes.IndexByte(serverVersion, byte(0)); idx > -1 {
serverVersion = serverVersion[:idx]
}
fde.serverVersion = serverVersion
data, err = readLittleEndian(data, &fde.createdTimestamp)
if err != nil {
return raw, errors.Wrap(err, "Failed to read created timestamp")
}
var totalHeaderSize uint8
data, err = readLittleEndian(data, &totalHeaderSize)
if err != nil {
return raw, errors.Wrap(err, "Failed to read total header size")
}
fde.extraHeadersSize = int(totalHeaderSize) - sizeOfBasicV4EventHeader
numEvents := len(mysql_proto.LogEventType_Type_value)
hasChecksum := true
if len(data) == 27 { // mysql 5.5(.37)
numEvents = 28
hasChecksum = false
} else if len(data) == 40 { // mysql 5.6(.17)
// This is a relay log where the master is 5.5 and slave is 5.6
if data[int(mysql_proto.LogEventType_WRITE_ROWS_EVENT)-1] == 0 {
numEvents = 28
}
} else {
return raw, errors.Newf(
"Unable to parse FDE for mysql variant: %s",
fde.serverVersion)
}
// unknown event's fixed length is implicit.
fde.fixedLengthSizes[mysql_proto.LogEventType_UNKNOWN_EVENT] = 0
for i := 1; i < numEvents; i++ {
fde.fixedLengthSizes[mysql_proto.LogEventType_Type(i)] = int(data[i-1])
}
if hasChecksum {
fde.checksumAlgorithm = mysql_proto.ChecksumAlgorithm_Type(
data[len(data)-5])
raw.SetChecksumSize(4)
}
return fde, nil
} | [
"func",
"(",
"p",
"*",
"FormatDescriptionEventParser",
")",
"Parse",
"(",
"raw",
"*",
"RawV4Event",
")",
"(",
"Event",
",",
"error",
")",
"{",
"fde",
":=",
"&",
"FormatDescriptionEvent",
"{",
"Event",
":",
"raw",
",",
"fixedLengthSizes",
":",
"make",
"(",
"map",
"[",
"mysql_proto",
".",
"LogEventType_Type",
"]",
"int",
")",
",",
"}",
"\n\n",
"data",
":=",
"raw",
".",
"VariableLengthData",
"(",
")",
"\n\n",
"data",
",",
"err",
":=",
"readLittleEndian",
"(",
"data",
",",
"&",
"fde",
".",
"binlogVersion",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"serverVersion",
",",
"data",
",",
"err",
":=",
"readSlice",
"(",
"data",
",",
"50",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"idx",
":=",
"bytes",
".",
"IndexByte",
"(",
"serverVersion",
",",
"byte",
"(",
"0",
")",
")",
";",
"idx",
">",
"-",
"1",
"{",
"serverVersion",
"=",
"serverVersion",
"[",
":",
"idx",
"]",
"\n",
"}",
"\n",
"fde",
".",
"serverVersion",
"=",
"serverVersion",
"\n\n",
"data",
",",
"err",
"=",
"readLittleEndian",
"(",
"data",
",",
"&",
"fde",
".",
"createdTimestamp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"totalHeaderSize",
"uint8",
"\n",
"data",
",",
"err",
"=",
"readLittleEndian",
"(",
"data",
",",
"&",
"totalHeaderSize",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"raw",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"fde",
".",
"extraHeadersSize",
"=",
"int",
"(",
"totalHeaderSize",
")",
"-",
"sizeOfBasicV4EventHeader",
"\n\n",
"numEvents",
":=",
"len",
"(",
"mysql_proto",
".",
"LogEventType_Type_value",
")",
"\n",
"hasChecksum",
":=",
"true",
"\n\n",
"if",
"len",
"(",
"data",
")",
"==",
"27",
"{",
"// mysql 5.5(.37)",
"numEvents",
"=",
"28",
"\n",
"hasChecksum",
"=",
"false",
"\n",
"}",
"else",
"if",
"len",
"(",
"data",
")",
"==",
"40",
"{",
"// mysql 5.6(.17)",
"// This is a relay log where the master is 5.5 and slave is 5.6",
"if",
"data",
"[",
"int",
"(",
"mysql_proto",
".",
"LogEventType_WRITE_ROWS_EVENT",
")",
"-",
"1",
"]",
"==",
"0",
"{",
"numEvents",
"=",
"28",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"raw",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"fde",
".",
"serverVersion",
")",
"\n",
"}",
"\n\n",
"// unknown event's fixed length is implicit.",
"fde",
".",
"fixedLengthSizes",
"[",
"mysql_proto",
".",
"LogEventType_UNKNOWN_EVENT",
"]",
"=",
"0",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"numEvents",
";",
"i",
"++",
"{",
"fde",
".",
"fixedLengthSizes",
"[",
"mysql_proto",
".",
"LogEventType_Type",
"(",
"i",
")",
"]",
"=",
"int",
"(",
"data",
"[",
"i",
"-",
"1",
"]",
")",
"\n",
"}",
"\n\n",
"if",
"hasChecksum",
"{",
"fde",
".",
"checksumAlgorithm",
"=",
"mysql_proto",
".",
"ChecksumAlgorithm_Type",
"(",
"data",
"[",
"len",
"(",
"data",
")",
"-",
"5",
"]",
")",
"\n\n",
"raw",
".",
"SetChecksumSize",
"(",
"4",
")",
"\n",
"}",
"\n\n",
"return",
"fde",
",",
"nil",
"\n",
"}"
] | // FormatDecriptionEventParser's Parse processes a raw FDE event into a
// FormatDescriptionEvent. | [
"FormatDecriptionEventParser",
"s",
"Parse",
"processes",
"a",
"raw",
"FDE",
"event",
"into",
"a",
"FormatDescriptionEvent",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/format_description_event.go#L116-L182 | train |
dropbox/godropbox | lockstore/store.go | New | func New(options LockStoreOptions) LockStore {
testTryLockCallback := options.testTryLockCallback
if testTryLockCallback == nil {
testTryLockCallback = func() {}
}
lock := _LockStoreImp{
granularity: options.Granularity,
testTryLockCallback: testTryLockCallback,
}
switch options.Granularity {
case PerKeyGranularity:
lock.perKeyLocks = make(map[string]*_LockImp)
case ShardedGranularity:
lock.shardedLocks = make([]*sync.RWMutex, options.LockCount)
for i := range lock.shardedLocks {
lock.shardedLocks[i] = &sync.RWMutex{}
}
}
return &lock
} | go | func New(options LockStoreOptions) LockStore {
testTryLockCallback := options.testTryLockCallback
if testTryLockCallback == nil {
testTryLockCallback = func() {}
}
lock := _LockStoreImp{
granularity: options.Granularity,
testTryLockCallback: testTryLockCallback,
}
switch options.Granularity {
case PerKeyGranularity:
lock.perKeyLocks = make(map[string]*_LockImp)
case ShardedGranularity:
lock.shardedLocks = make([]*sync.RWMutex, options.LockCount)
for i := range lock.shardedLocks {
lock.shardedLocks[i] = &sync.RWMutex{}
}
}
return &lock
} | [
"func",
"New",
"(",
"options",
"LockStoreOptions",
")",
"LockStore",
"{",
"testTryLockCallback",
":=",
"options",
".",
"testTryLockCallback",
"\n",
"if",
"testTryLockCallback",
"==",
"nil",
"{",
"testTryLockCallback",
"=",
"func",
"(",
")",
"{",
"}",
"\n",
"}",
"\n\n",
"lock",
":=",
"_LockStoreImp",
"{",
"granularity",
":",
"options",
".",
"Granularity",
",",
"testTryLockCallback",
":",
"testTryLockCallback",
",",
"}",
"\n\n",
"switch",
"options",
".",
"Granularity",
"{",
"case",
"PerKeyGranularity",
":",
"lock",
".",
"perKeyLocks",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"_LockImp",
")",
"\n",
"case",
"ShardedGranularity",
":",
"lock",
".",
"shardedLocks",
"=",
"make",
"(",
"[",
"]",
"*",
"sync",
".",
"RWMutex",
",",
"options",
".",
"LockCount",
")",
"\n",
"for",
"i",
":=",
"range",
"lock",
".",
"shardedLocks",
"{",
"lock",
".",
"shardedLocks",
"[",
"i",
"]",
"=",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"lock",
"\n",
"}"
] | // New creates a new LockStore given the options | [
"New",
"creates",
"a",
"new",
"LockStore",
"given",
"the",
"options"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/store.go#L91-L113 | train |
dropbox/godropbox | memcache/sharded_client.go | NewShardedClient | func NewShardedClient(
manager ShardManager,
builder ClientShardBuilder) Client {
return &ShardedClient{
manager: manager,
builder: builder,
}
} | go | func NewShardedClient(
manager ShardManager,
builder ClientShardBuilder) Client {
return &ShardedClient{
manager: manager,
builder: builder,
}
} | [
"func",
"NewShardedClient",
"(",
"manager",
"ShardManager",
",",
"builder",
"ClientShardBuilder",
")",
"Client",
"{",
"return",
"&",
"ShardedClient",
"{",
"manager",
":",
"manager",
",",
"builder",
":",
"builder",
",",
"}",
"\n",
"}"
] | // This creates a new ShardedClient. | [
"This",
"creates",
"a",
"new",
"ShardedClient",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L24-L32 | train |
dropbox/godropbox | memcache/sharded_client.go | setMultiMutator | func setMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.SetMulti(mapping.Items)
} | go | func setMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.SetMulti(mapping.Items)
} | [
"func",
"setMultiMutator",
"(",
"shardClient",
"Client",
",",
"mapping",
"*",
"ShardMapping",
")",
"[",
"]",
"MutateResponse",
"{",
"return",
"shardClient",
".",
"SetMulti",
"(",
"mapping",
".",
"Items",
")",
"\n",
"}"
] | // A helper used to specify a SetMulti mutation operation on a shard client. | [
"A",
"helper",
"used",
"to",
"specify",
"a",
"SetMulti",
"mutation",
"operation",
"on",
"a",
"shard",
"client",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L260-L262 | train |
dropbox/godropbox | memcache/sharded_client.go | casMultiMutator | func casMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.CasMulti(mapping.Items)
} | go | func casMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.CasMulti(mapping.Items)
} | [
"func",
"casMultiMutator",
"(",
"shardClient",
"Client",
",",
"mapping",
"*",
"ShardMapping",
")",
"[",
"]",
"MutateResponse",
"{",
"return",
"shardClient",
".",
"CasMulti",
"(",
"mapping",
".",
"Items",
")",
"\n",
"}"
] | // A helper used to specify a CasMulti mutation operation on a shard client. | [
"A",
"helper",
"used",
"to",
"specify",
"a",
"CasMulti",
"mutation",
"operation",
"on",
"a",
"shard",
"client",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L265-L267 | train |
dropbox/godropbox | memcache/sharded_client.go | addMultiMutator | func addMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.AddMulti(mapping.Items)
} | go | func addMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.AddMulti(mapping.Items)
} | [
"func",
"addMultiMutator",
"(",
"shardClient",
"Client",
",",
"mapping",
"*",
"ShardMapping",
")",
"[",
"]",
"MutateResponse",
"{",
"return",
"shardClient",
".",
"AddMulti",
"(",
"mapping",
".",
"Items",
")",
"\n",
"}"
] | // A helper used to specify a AddMulti mutation operation on a shard client. | [
"A",
"helper",
"used",
"to",
"specify",
"a",
"AddMulti",
"mutation",
"operation",
"on",
"a",
"shard",
"client",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L299-L301 | train |
dropbox/godropbox | memcache/sharded_client.go | deleteMultiMutator | func deleteMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.DeleteMulti(mapping.Keys)
} | go | func deleteMultiMutator(shardClient Client, mapping *ShardMapping) []MutateResponse {
return shardClient.DeleteMulti(mapping.Keys)
} | [
"func",
"deleteMultiMutator",
"(",
"shardClient",
"Client",
",",
"mapping",
"*",
"ShardMapping",
")",
"[",
"]",
"MutateResponse",
"{",
"return",
"shardClient",
".",
"DeleteMulti",
"(",
"mapping",
".",
"Keys",
")",
"\n",
"}"
] | // A helper used to specify a DeleteMulti mutation operation on a shard client. | [
"A",
"helper",
"used",
"to",
"specify",
"a",
"DeleteMulti",
"mutation",
"operation",
"on",
"a",
"shard",
"client",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/sharded_client.go#L327-L329 | train |
dropbox/godropbox | database/binlog/event_parser.go | NewV4EventParserMap | func NewV4EventParserMap() V4EventParserMap {
m := &v4EventParserMap{
extraHeadersSize: nonFDEExtraHeadersSize,
checksumSize: 0,
parsers: make(map[mysql_proto.LogEventType_Type]V4EventParser),
}
// TODO(patrick): implement parsers
m.set(&FormatDescriptionEventParser{})
m.set(&QueryEventParser{})
m.set(&RotateEventParser{})
m.set(&TableMapEventParser{})
m.set(&XidEventParser{})
m.set(&RowsQueryEventParser{})
m.set(&GtidLogEventParser{})
m.set(&PreviousGtidsLogEventParser{})
m.set(newWriteRowsEventV1Parser())
m.set(newWriteRowsEventV2Parser())
m.set(newUpdateRowsEventV1Parser())
m.set(newUpdateRowsEventV2Parser())
m.set(newDeleteRowsEventV1Parser())
m.set(newDeleteRowsEventV2Parser())
m.set(newStopEventParser())
m.numSupportedEventTypes = len(mysql_proto.LogEventType_Type_name)
return m
} | go | func NewV4EventParserMap() V4EventParserMap {
m := &v4EventParserMap{
extraHeadersSize: nonFDEExtraHeadersSize,
checksumSize: 0,
parsers: make(map[mysql_proto.LogEventType_Type]V4EventParser),
}
// TODO(patrick): implement parsers
m.set(&FormatDescriptionEventParser{})
m.set(&QueryEventParser{})
m.set(&RotateEventParser{})
m.set(&TableMapEventParser{})
m.set(&XidEventParser{})
m.set(&RowsQueryEventParser{})
m.set(&GtidLogEventParser{})
m.set(&PreviousGtidsLogEventParser{})
m.set(newWriteRowsEventV1Parser())
m.set(newWriteRowsEventV2Parser())
m.set(newUpdateRowsEventV1Parser())
m.set(newUpdateRowsEventV2Parser())
m.set(newDeleteRowsEventV1Parser())
m.set(newDeleteRowsEventV2Parser())
m.set(newStopEventParser())
m.numSupportedEventTypes = len(mysql_proto.LogEventType_Type_name)
return m
} | [
"func",
"NewV4EventParserMap",
"(",
")",
"V4EventParserMap",
"{",
"m",
":=",
"&",
"v4EventParserMap",
"{",
"extraHeadersSize",
":",
"nonFDEExtraHeadersSize",
",",
"checksumSize",
":",
"0",
",",
"parsers",
":",
"make",
"(",
"map",
"[",
"mysql_proto",
".",
"LogEventType_Type",
"]",
"V4EventParser",
")",
",",
"}",
"\n\n",
"// TODO(patrick): implement parsers",
"m",
".",
"set",
"(",
"&",
"FormatDescriptionEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"QueryEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"RotateEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"TableMapEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"XidEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"RowsQueryEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"GtidLogEventParser",
"{",
"}",
")",
"\n",
"m",
".",
"set",
"(",
"&",
"PreviousGtidsLogEventParser",
"{",
"}",
")",
"\n\n",
"m",
".",
"set",
"(",
"newWriteRowsEventV1Parser",
"(",
")",
")",
"\n",
"m",
".",
"set",
"(",
"newWriteRowsEventV2Parser",
"(",
")",
")",
"\n",
"m",
".",
"set",
"(",
"newUpdateRowsEventV1Parser",
"(",
")",
")",
"\n",
"m",
".",
"set",
"(",
"newUpdateRowsEventV2Parser",
"(",
")",
")",
"\n",
"m",
".",
"set",
"(",
"newDeleteRowsEventV1Parser",
"(",
")",
")",
"\n",
"m",
".",
"set",
"(",
"newDeleteRowsEventV2Parser",
"(",
")",
")",
"\n",
"m",
".",
"set",
"(",
"newStopEventParser",
"(",
")",
")",
"\n\n",
"m",
".",
"numSupportedEventTypes",
"=",
"len",
"(",
"mysql_proto",
".",
"LogEventType_Type_name",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // NewV4EventParserMap returns an initialize V4EventParserMap with all handled
// event types' parsers registered. | [
"NewV4EventParserMap",
"returns",
"an",
"initialize",
"V4EventParserMap",
"with",
"all",
"handled",
"event",
"types",
"parsers",
"registered",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event_parser.go#L92-L119 | train |
dropbox/godropbox | errors/errors.go | GetMessage | func GetMessage(err interface{}) string {
switch e := err.(type) {
case DropboxError:
return extractFullErrorMessage(e, false)
case runtime.Error:
return runtime.Error(e).Error()
case error:
return e.Error()
default:
return "Passed a non-error to GetMessage"
}
} | go | func GetMessage(err interface{}) string {
switch e := err.(type) {
case DropboxError:
return extractFullErrorMessage(e, false)
case runtime.Error:
return runtime.Error(e).Error()
case error:
return e.Error()
default:
return "Passed a non-error to GetMessage"
}
} | [
"func",
"GetMessage",
"(",
"err",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"e",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"DropboxError",
":",
"return",
"extractFullErrorMessage",
"(",
"e",
",",
"false",
")",
"\n",
"case",
"runtime",
".",
"Error",
":",
"return",
"runtime",
".",
"Error",
"(",
"e",
")",
".",
"Error",
"(",
")",
"\n",
"case",
"error",
":",
"return",
"e",
".",
"Error",
"(",
")",
"\n",
"default",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}"
] | // This returns the error string without stack trace information. | [
"This",
"returns",
"the",
"error",
"string",
"without",
"stack",
"trace",
"information",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L72-L83 | train |
dropbox/godropbox | errors/errors.go | Newf | func Newf(format string, args ...interface{}) DropboxError {
return new(nil, fmt.Sprintf(format, args...))
} | go | func Newf(format string, args ...interface{}) DropboxError {
return new(nil, fmt.Sprintf(format, args...))
} | [
"func",
"Newf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"DropboxError",
"{",
"return",
"new",
"(",
"nil",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}"
] | // Same as New, but with fmt.Printf-style parameters. | [
"Same",
"as",
"New",
"but",
"with",
"fmt",
".",
"Printf",
"-",
"style",
"parameters",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L148-L150 | train |
dropbox/godropbox | errors/errors.go | Wrapf | func Wrapf(err error, format string, args ...interface{}) DropboxError {
return new(err, fmt.Sprintf(format, args...))
} | go | func Wrapf(err error, format string, args ...interface{}) DropboxError {
return new(err, fmt.Sprintf(format, args...))
} | [
"func",
"Wrapf",
"(",
"err",
"error",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"DropboxError",
"{",
"return",
"new",
"(",
"err",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}"
] | // Same as Wrap, but with fmt.Printf-style parameters. | [
"Same",
"as",
"Wrap",
"but",
"with",
"fmt",
".",
"Printf",
"-",
"style",
"parameters",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L158-L160 | train |
dropbox/godropbox | errors/errors.go | new | func new(err error, msg string) *baseError {
stack := make([]uintptr, 200)
stackLength := runtime.Callers(3, stack)
return &baseError{
msg: msg,
stack: stack[:stackLength],
inner: err,
}
} | go | func new(err error, msg string) *baseError {
stack := make([]uintptr, 200)
stackLength := runtime.Callers(3, stack)
return &baseError{
msg: msg,
stack: stack[:stackLength],
inner: err,
}
} | [
"func",
"new",
"(",
"err",
"error",
",",
"msg",
"string",
")",
"*",
"baseError",
"{",
"stack",
":=",
"make",
"(",
"[",
"]",
"uintptr",
",",
"200",
")",
"\n",
"stackLength",
":=",
"runtime",
".",
"Callers",
"(",
"3",
",",
"stack",
")",
"\n",
"return",
"&",
"baseError",
"{",
"msg",
":",
"msg",
",",
"stack",
":",
"stack",
"[",
":",
"stackLength",
"]",
",",
"inner",
":",
"err",
",",
"}",
"\n",
"}"
] | // Internal helper function to create new baseError objects,
// note that if there is more than one level of redirection to call this function,
// stack frame information will include that level too. | [
"Internal",
"helper",
"function",
"to",
"create",
"new",
"baseError",
"objects",
"note",
"that",
"if",
"there",
"is",
"more",
"than",
"one",
"level",
"of",
"redirection",
"to",
"call",
"this",
"function",
"stack",
"frame",
"information",
"will",
"include",
"that",
"level",
"too",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L165-L173 | train |
dropbox/godropbox | errors/errors.go | extractFullErrorMessage | func extractFullErrorMessage(e DropboxError, includeStack bool) string {
var ok bool
var lastDbxErr DropboxError
errMsg := bytes.NewBuffer(make([]byte, 0, 1024))
dbxErr := e
for {
lastDbxErr = dbxErr
errMsg.WriteString(dbxErr.GetMessage())
innerErr := dbxErr.GetInner()
if innerErr == nil {
break
}
dbxErr, ok = innerErr.(DropboxError)
if !ok {
// We have reached the end and traveresed all inner errors.
// Add last message and exit loop.
errMsg.WriteString(innerErr.Error())
break
}
errMsg.WriteString("\n")
}
if includeStack {
errMsg.WriteString("\nORIGINAL STACK TRACE:\n")
errMsg.WriteString(lastDbxErr.GetStack())
}
return errMsg.String()
} | go | func extractFullErrorMessage(e DropboxError, includeStack bool) string {
var ok bool
var lastDbxErr DropboxError
errMsg := bytes.NewBuffer(make([]byte, 0, 1024))
dbxErr := e
for {
lastDbxErr = dbxErr
errMsg.WriteString(dbxErr.GetMessage())
innerErr := dbxErr.GetInner()
if innerErr == nil {
break
}
dbxErr, ok = innerErr.(DropboxError)
if !ok {
// We have reached the end and traveresed all inner errors.
// Add last message and exit loop.
errMsg.WriteString(innerErr.Error())
break
}
errMsg.WriteString("\n")
}
if includeStack {
errMsg.WriteString("\nORIGINAL STACK TRACE:\n")
errMsg.WriteString(lastDbxErr.GetStack())
}
return errMsg.String()
} | [
"func",
"extractFullErrorMessage",
"(",
"e",
"DropboxError",
",",
"includeStack",
"bool",
")",
"string",
"{",
"var",
"ok",
"bool",
"\n",
"var",
"lastDbxErr",
"DropboxError",
"\n",
"errMsg",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"1024",
")",
")",
"\n\n",
"dbxErr",
":=",
"e",
"\n",
"for",
"{",
"lastDbxErr",
"=",
"dbxErr",
"\n",
"errMsg",
".",
"WriteString",
"(",
"dbxErr",
".",
"GetMessage",
"(",
")",
")",
"\n\n",
"innerErr",
":=",
"dbxErr",
".",
"GetInner",
"(",
")",
"\n",
"if",
"innerErr",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"dbxErr",
",",
"ok",
"=",
"innerErr",
".",
"(",
"DropboxError",
")",
"\n",
"if",
"!",
"ok",
"{",
"// We have reached the end and traveresed all inner errors.",
"// Add last message and exit loop.",
"errMsg",
".",
"WriteString",
"(",
"innerErr",
".",
"Error",
"(",
")",
")",
"\n",
"break",
"\n",
"}",
"\n",
"errMsg",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"if",
"includeStack",
"{",
"errMsg",
".",
"WriteString",
"(",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"errMsg",
".",
"WriteString",
"(",
"lastDbxErr",
".",
"GetStack",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"errMsg",
".",
"String",
"(",
")",
"\n",
"}"
] | // Constructs full error message for a given DropboxError by traversing
// all of its inner errors. If includeStack is True it will also include
// stack trace from deepest DropboxError in the chain. | [
"Constructs",
"full",
"error",
"message",
"for",
"a",
"given",
"DropboxError",
"by",
"traversing",
"all",
"of",
"its",
"inner",
"errors",
".",
"If",
"includeStack",
"is",
"True",
"it",
"will",
"also",
"include",
"stack",
"trace",
"from",
"deepest",
"DropboxError",
"in",
"the",
"chain",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L178-L206 | train |
dropbox/godropbox | errors/errors.go | unwrapError | func unwrapError(ierr error) (nerr error) {
// Internal errors have a well defined bit of context.
if dbxErr, ok := ierr.(DropboxError); ok {
return dbxErr.GetInner()
}
// At this point, if anything goes wrong, just return nil.
defer func() {
if x := recover(); x != nil {
nerr = nil
}
}()
// Go system errors have a convention but paradoxically no
// interface. All of these panic on error.
errV := reflect.ValueOf(ierr).Elem()
errV = errV.FieldByName("Err")
return errV.Interface().(error)
} | go | func unwrapError(ierr error) (nerr error) {
// Internal errors have a well defined bit of context.
if dbxErr, ok := ierr.(DropboxError); ok {
return dbxErr.GetInner()
}
// At this point, if anything goes wrong, just return nil.
defer func() {
if x := recover(); x != nil {
nerr = nil
}
}()
// Go system errors have a convention but paradoxically no
// interface. All of these panic on error.
errV := reflect.ValueOf(ierr).Elem()
errV = errV.FieldByName("Err")
return errV.Interface().(error)
} | [
"func",
"unwrapError",
"(",
"ierr",
"error",
")",
"(",
"nerr",
"error",
")",
"{",
"// Internal errors have a well defined bit of context.",
"if",
"dbxErr",
",",
"ok",
":=",
"ierr",
".",
"(",
"DropboxError",
")",
";",
"ok",
"{",
"return",
"dbxErr",
".",
"GetInner",
"(",
")",
"\n",
"}",
"\n\n",
"// At this point, if anything goes wrong, just return nil.",
"defer",
"func",
"(",
")",
"{",
"if",
"x",
":=",
"recover",
"(",
")",
";",
"x",
"!=",
"nil",
"{",
"nerr",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Go system errors have a convention but paradoxically no",
"// interface. All of these panic on error.",
"errV",
":=",
"reflect",
".",
"ValueOf",
"(",
"ierr",
")",
".",
"Elem",
"(",
")",
"\n",
"errV",
"=",
"errV",
".",
"FieldByName",
"(",
"\"",
"\"",
")",
"\n",
"return",
"errV",
".",
"Interface",
"(",
")",
".",
"(",
"error",
")",
"\n",
"}"
] | // Return a wrapped error or nil if there is none. | [
"Return",
"a",
"wrapped",
"error",
"or",
"nil",
"if",
"there",
"is",
"none",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L209-L227 | train |
dropbox/godropbox | errors/errors.go | RootError | func RootError(ierr error) (nerr error) {
nerr = ierr
for i := 0; i < 20; i++ {
terr := unwrapError(nerr)
if terr == nil {
return nerr
}
nerr = terr
}
return fmt.Errorf("too many iterations: %T", nerr)
} | go | func RootError(ierr error) (nerr error) {
nerr = ierr
for i := 0; i < 20; i++ {
terr := unwrapError(nerr)
if terr == nil {
return nerr
}
nerr = terr
}
return fmt.Errorf("too many iterations: %T", nerr)
} | [
"func",
"RootError",
"(",
"ierr",
"error",
")",
"(",
"nerr",
"error",
")",
"{",
"nerr",
"=",
"ierr",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"20",
";",
"i",
"++",
"{",
"terr",
":=",
"unwrapError",
"(",
"nerr",
")",
"\n",
"if",
"terr",
"==",
"nil",
"{",
"return",
"nerr",
"\n",
"}",
"\n",
"nerr",
"=",
"terr",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"nerr",
")",
"\n",
"}"
] | // Keep peeling away layers or context until a primitive error is revealed. | [
"Keep",
"peeling",
"away",
"layers",
"or",
"context",
"until",
"a",
"primitive",
"error",
"is",
"revealed",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L230-L240 | train |
dropbox/godropbox | errors/errors.go | IsError | func IsError(err, errConst error) bool {
if err == errConst {
return true
}
// Must rely on string equivalence, otherwise a value is not equal
// to its pointer value.
rootErrStr := ""
rootErr := RootError(err)
if rootErr != nil {
rootErrStr = rootErr.Error()
}
errConstStr := ""
if errConst != nil {
errConstStr = errConst.Error()
}
return rootErrStr == errConstStr
} | go | func IsError(err, errConst error) bool {
if err == errConst {
return true
}
// Must rely on string equivalence, otherwise a value is not equal
// to its pointer value.
rootErrStr := ""
rootErr := RootError(err)
if rootErr != nil {
rootErrStr = rootErr.Error()
}
errConstStr := ""
if errConst != nil {
errConstStr = errConst.Error()
}
return rootErrStr == errConstStr
} | [
"func",
"IsError",
"(",
"err",
",",
"errConst",
"error",
")",
"bool",
"{",
"if",
"err",
"==",
"errConst",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// Must rely on string equivalence, otherwise a value is not equal",
"// to its pointer value.",
"rootErrStr",
":=",
"\"",
"\"",
"\n",
"rootErr",
":=",
"RootError",
"(",
"err",
")",
"\n",
"if",
"rootErr",
"!=",
"nil",
"{",
"rootErrStr",
"=",
"rootErr",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"errConstStr",
":=",
"\"",
"\"",
"\n",
"if",
"errConst",
"!=",
"nil",
"{",
"errConstStr",
"=",
"errConst",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"return",
"rootErrStr",
"==",
"errConstStr",
"\n",
"}"
] | // Perform a deep check, unwrapping errors as much as possilbe and
// comparing the string version of the error. | [
"Perform",
"a",
"deep",
"check",
"unwrapping",
"errors",
"as",
"much",
"as",
"possilbe",
"and",
"comparing",
"the",
"string",
"version",
"of",
"the",
"error",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/errors/errors.go#L244-L260 | train |
dropbox/godropbox | database/binlog/rows_query_event.go | Parse | func (p *RowsQueryEventParser) Parse(raw *RawV4Event) (Event, error) {
query := &RowsQueryEvent{
Event: raw,
}
data := raw.VariableLengthData()
if len(data) < 1 {
return raw, errors.Newf("Invalid message length")
}
query.truncatedQuery = data[1:]
return query, nil
} | go | func (p *RowsQueryEventParser) Parse(raw *RawV4Event) (Event, error) {
query := &RowsQueryEvent{
Event: raw,
}
data := raw.VariableLengthData()
if len(data) < 1 {
return raw, errors.Newf("Invalid message length")
}
query.truncatedQuery = data[1:]
return query, nil
} | [
"func",
"(",
"p",
"*",
"RowsQueryEventParser",
")",
"Parse",
"(",
"raw",
"*",
"RawV4Event",
")",
"(",
"Event",
",",
"error",
")",
"{",
"query",
":=",
"&",
"RowsQueryEvent",
"{",
"Event",
":",
"raw",
",",
"}",
"\n\n",
"data",
":=",
"raw",
".",
"VariableLengthData",
"(",
")",
"\n",
"if",
"len",
"(",
"data",
")",
"<",
"1",
"{",
"return",
"raw",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"query",
".",
"truncatedQuery",
"=",
"data",
"[",
"1",
":",
"]",
"\n\n",
"return",
"query",
",",
"nil",
"\n",
"}"
] | // RowsQueryEventParser's Parse processes a raw query event into a
// RowsQueryEvent. | [
"RowsQueryEventParser",
"s",
"Parse",
"processes",
"a",
"raw",
"query",
"event",
"into",
"a",
"RowsQueryEvent",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/rows_query_event.go#L49-L62 | train |
dropbox/godropbox | resource_pool/simple_resource_pool.go | NewSimpleResourcePool | func NewSimpleResourcePool(options Options) ResourcePool {
numActive := new(int32)
atomic.StoreInt32(numActive, 0)
activeHighWaterMark := new(int32)
atomic.StoreInt32(activeHighWaterMark, 0)
var tokens sync2.Semaphore
if options.OpenMaxConcurrency > 0 {
tokens = sync2.NewBoundedSemaphore(uint(options.OpenMaxConcurrency))
}
return &simpleResourcePool{
location: "",
options: options,
numActive: numActive,
activeHighWaterMark: activeHighWaterMark,
openTokens: tokens,
mutex: sync.Mutex{},
idleHandles: make([]*idleHandle, 0, 0),
isLameDuck: false,
}
} | go | func NewSimpleResourcePool(options Options) ResourcePool {
numActive := new(int32)
atomic.StoreInt32(numActive, 0)
activeHighWaterMark := new(int32)
atomic.StoreInt32(activeHighWaterMark, 0)
var tokens sync2.Semaphore
if options.OpenMaxConcurrency > 0 {
tokens = sync2.NewBoundedSemaphore(uint(options.OpenMaxConcurrency))
}
return &simpleResourcePool{
location: "",
options: options,
numActive: numActive,
activeHighWaterMark: activeHighWaterMark,
openTokens: tokens,
mutex: sync.Mutex{},
idleHandles: make([]*idleHandle, 0, 0),
isLameDuck: false,
}
} | [
"func",
"NewSimpleResourcePool",
"(",
"options",
"Options",
")",
"ResourcePool",
"{",
"numActive",
":=",
"new",
"(",
"int32",
")",
"\n",
"atomic",
".",
"StoreInt32",
"(",
"numActive",
",",
"0",
")",
"\n\n",
"activeHighWaterMark",
":=",
"new",
"(",
"int32",
")",
"\n",
"atomic",
".",
"StoreInt32",
"(",
"activeHighWaterMark",
",",
"0",
")",
"\n\n",
"var",
"tokens",
"sync2",
".",
"Semaphore",
"\n",
"if",
"options",
".",
"OpenMaxConcurrency",
">",
"0",
"{",
"tokens",
"=",
"sync2",
".",
"NewBoundedSemaphore",
"(",
"uint",
"(",
"options",
".",
"OpenMaxConcurrency",
")",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"simpleResourcePool",
"{",
"location",
":",
"\"",
"\"",
",",
"options",
":",
"options",
",",
"numActive",
":",
"numActive",
",",
"activeHighWaterMark",
":",
"activeHighWaterMark",
",",
"openTokens",
":",
"tokens",
",",
"mutex",
":",
"sync",
".",
"Mutex",
"{",
"}",
",",
"idleHandles",
":",
"make",
"(",
"[",
"]",
"*",
"idleHandle",
",",
"0",
",",
"0",
")",
",",
"isLameDuck",
":",
"false",
",",
"}",
"\n",
"}"
] | // This returns a SimpleResourcePool, where all handles are associated to a
// single resource location. | [
"This",
"returns",
"a",
"SimpleResourcePool",
"where",
"all",
"handles",
"are",
"associated",
"to",
"a",
"single",
"resource",
"location",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L54-L76 | train |
dropbox/godropbox | resource_pool/simple_resource_pool.go | getIdleHandle | func (p *simpleResourcePool) getIdleHandle() ManagedHandle {
var toClose []*idleHandle
defer func() {
// NOTE: Must keep the closure around to late bind the toClose slice.
p.closeHandles(toClose)
}()
now := p.options.getCurrentTime()
p.mutex.Lock()
defer p.mutex.Unlock()
var i int
for i = 0; i < len(p.idleHandles); i++ {
idle := p.idleHandles[i]
if idle.keepUntil == nil || now.Before(*idle.keepUntil) {
break
}
}
if i > 0 {
toClose = p.idleHandles[0:i]
}
if i < len(p.idleHandles) {
idle := p.idleHandles[i]
p.idleHandles = p.idleHandles[i+1:]
return NewManagedHandle(p.location, idle.handle, p, p.options)
}
if len(p.idleHandles) > 0 {
p.idleHandles = []*idleHandle{}
}
return nil
} | go | func (p *simpleResourcePool) getIdleHandle() ManagedHandle {
var toClose []*idleHandle
defer func() {
// NOTE: Must keep the closure around to late bind the toClose slice.
p.closeHandles(toClose)
}()
now := p.options.getCurrentTime()
p.mutex.Lock()
defer p.mutex.Unlock()
var i int
for i = 0; i < len(p.idleHandles); i++ {
idle := p.idleHandles[i]
if idle.keepUntil == nil || now.Before(*idle.keepUntil) {
break
}
}
if i > 0 {
toClose = p.idleHandles[0:i]
}
if i < len(p.idleHandles) {
idle := p.idleHandles[i]
p.idleHandles = p.idleHandles[i+1:]
return NewManagedHandle(p.location, idle.handle, p, p.options)
}
if len(p.idleHandles) > 0 {
p.idleHandles = []*idleHandle{}
}
return nil
} | [
"func",
"(",
"p",
"*",
"simpleResourcePool",
")",
"getIdleHandle",
"(",
")",
"ManagedHandle",
"{",
"var",
"toClose",
"[",
"]",
"*",
"idleHandle",
"\n",
"defer",
"func",
"(",
")",
"{",
"// NOTE: Must keep the closure around to late bind the toClose slice.",
"p",
".",
"closeHandles",
"(",
"toClose",
")",
"\n",
"}",
"(",
")",
"\n\n",
"now",
":=",
"p",
".",
"options",
".",
"getCurrentTime",
"(",
")",
"\n\n",
"p",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"i",
"int",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"len",
"(",
"p",
".",
"idleHandles",
")",
";",
"i",
"++",
"{",
"idle",
":=",
"p",
".",
"idleHandles",
"[",
"i",
"]",
"\n",
"if",
"idle",
".",
"keepUntil",
"==",
"nil",
"||",
"now",
".",
"Before",
"(",
"*",
"idle",
".",
"keepUntil",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"i",
">",
"0",
"{",
"toClose",
"=",
"p",
".",
"idleHandles",
"[",
"0",
":",
"i",
"]",
"\n",
"}",
"\n\n",
"if",
"i",
"<",
"len",
"(",
"p",
".",
"idleHandles",
")",
"{",
"idle",
":=",
"p",
".",
"idleHandles",
"[",
"i",
"]",
"\n",
"p",
".",
"idleHandles",
"=",
"p",
".",
"idleHandles",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"return",
"NewManagedHandle",
"(",
"p",
".",
"location",
",",
"idle",
".",
"handle",
",",
"p",
",",
"p",
".",
"options",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"p",
".",
"idleHandles",
")",
">",
"0",
"{",
"p",
".",
"idleHandles",
"=",
"[",
"]",
"*",
"idleHandle",
"{",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // This returns an idle resource, if there is one. | [
"This",
"returns",
"an",
"idle",
"resource",
"if",
"there",
"is",
"one",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L263-L296 | train |
dropbox/godropbox | resource_pool/simple_resource_pool.go | queueIdleHandles | func (p *simpleResourcePool) queueIdleHandles(handle interface{}) {
var toClose []*idleHandle
defer func() {
// NOTE: Must keep the closure around to late bind the toClose slice.
p.closeHandles(toClose)
}()
now := p.options.getCurrentTime()
var keepUntil *time.Time
if p.options.MaxIdleTime != nil {
// NOTE: Assign to temp variable first to work around compiler bug
x := now.Add(*p.options.MaxIdleTime)
keepUntil = &x
}
p.mutex.Lock()
defer p.mutex.Unlock()
if p.isLameDuck {
toClose = []*idleHandle{
{handle: handle},
}
return
}
p.idleHandles = append(
p.idleHandles,
&idleHandle{
handle: handle,
keepUntil: keepUntil,
})
nIdleHandles := uint32(len(p.idleHandles))
if nIdleHandles > p.options.MaxIdleHandles {
handlesToClose := nIdleHandles - p.options.MaxIdleHandles
toClose = p.idleHandles[0:handlesToClose]
p.idleHandles = p.idleHandles[handlesToClose:nIdleHandles]
}
} | go | func (p *simpleResourcePool) queueIdleHandles(handle interface{}) {
var toClose []*idleHandle
defer func() {
// NOTE: Must keep the closure around to late bind the toClose slice.
p.closeHandles(toClose)
}()
now := p.options.getCurrentTime()
var keepUntil *time.Time
if p.options.MaxIdleTime != nil {
// NOTE: Assign to temp variable first to work around compiler bug
x := now.Add(*p.options.MaxIdleTime)
keepUntil = &x
}
p.mutex.Lock()
defer p.mutex.Unlock()
if p.isLameDuck {
toClose = []*idleHandle{
{handle: handle},
}
return
}
p.idleHandles = append(
p.idleHandles,
&idleHandle{
handle: handle,
keepUntil: keepUntil,
})
nIdleHandles := uint32(len(p.idleHandles))
if nIdleHandles > p.options.MaxIdleHandles {
handlesToClose := nIdleHandles - p.options.MaxIdleHandles
toClose = p.idleHandles[0:handlesToClose]
p.idleHandles = p.idleHandles[handlesToClose:nIdleHandles]
}
} | [
"func",
"(",
"p",
"*",
"simpleResourcePool",
")",
"queueIdleHandles",
"(",
"handle",
"interface",
"{",
"}",
")",
"{",
"var",
"toClose",
"[",
"]",
"*",
"idleHandle",
"\n",
"defer",
"func",
"(",
")",
"{",
"// NOTE: Must keep the closure around to late bind the toClose slice.",
"p",
".",
"closeHandles",
"(",
"toClose",
")",
"\n",
"}",
"(",
")",
"\n\n",
"now",
":=",
"p",
".",
"options",
".",
"getCurrentTime",
"(",
")",
"\n",
"var",
"keepUntil",
"*",
"time",
".",
"Time",
"\n",
"if",
"p",
".",
"options",
".",
"MaxIdleTime",
"!=",
"nil",
"{",
"// NOTE: Assign to temp variable first to work around compiler bug",
"x",
":=",
"now",
".",
"Add",
"(",
"*",
"p",
".",
"options",
".",
"MaxIdleTime",
")",
"\n",
"keepUntil",
"=",
"&",
"x",
"\n",
"}",
"\n\n",
"p",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"p",
".",
"isLameDuck",
"{",
"toClose",
"=",
"[",
"]",
"*",
"idleHandle",
"{",
"{",
"handle",
":",
"handle",
"}",
",",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"idleHandles",
"=",
"append",
"(",
"p",
".",
"idleHandles",
",",
"&",
"idleHandle",
"{",
"handle",
":",
"handle",
",",
"keepUntil",
":",
"keepUntil",
",",
"}",
")",
"\n\n",
"nIdleHandles",
":=",
"uint32",
"(",
"len",
"(",
"p",
".",
"idleHandles",
")",
")",
"\n",
"if",
"nIdleHandles",
">",
"p",
".",
"options",
".",
"MaxIdleHandles",
"{",
"handlesToClose",
":=",
"nIdleHandles",
"-",
"p",
".",
"options",
".",
"MaxIdleHandles",
"\n",
"toClose",
"=",
"p",
".",
"idleHandles",
"[",
"0",
":",
"handlesToClose",
"]",
"\n",
"p",
".",
"idleHandles",
"=",
"p",
".",
"idleHandles",
"[",
"handlesToClose",
":",
"nIdleHandles",
"]",
"\n",
"}",
"\n",
"}"
] | // This adds an idle resource to the pool. | [
"This",
"adds",
"an",
"idle",
"resource",
"to",
"the",
"pool",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L299-L337 | train |
dropbox/godropbox | resource_pool/simple_resource_pool.go | closeHandles | func (p *simpleResourcePool) closeHandles(handles []*idleHandle) {
for _, handle := range handles {
_ = p.options.Close(handle.handle)
}
} | go | func (p *simpleResourcePool) closeHandles(handles []*idleHandle) {
for _, handle := range handles {
_ = p.options.Close(handle.handle)
}
} | [
"func",
"(",
"p",
"*",
"simpleResourcePool",
")",
"closeHandles",
"(",
"handles",
"[",
"]",
"*",
"idleHandle",
")",
"{",
"for",
"_",
",",
"handle",
":=",
"range",
"handles",
"{",
"_",
"=",
"p",
".",
"options",
".",
"Close",
"(",
"handle",
".",
"handle",
")",
"\n",
"}",
"\n",
"}"
] | // Closes resources, at this point it is assumed that this resources
// are no longer referenced from the main idleHandles slice. | [
"Closes",
"resources",
"at",
"this",
"point",
"it",
"is",
"assumed",
"that",
"this",
"resources",
"are",
"no",
"longer",
"referenced",
"from",
"the",
"main",
"idleHandles",
"slice",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/simple_resource_pool.go#L341-L345 | train |
dropbox/godropbox | database/sqlbuilder/table.go | NewTable | func NewTable(name string, columns ...NonAliasColumn) *Table {
if !validIdentifierName(name) {
panic("Invalid table name")
}
t := &Table{
name: name,
columns: columns,
columnLookup: make(map[string]NonAliasColumn),
}
for _, c := range columns {
err := c.setTableName(name)
if err != nil {
panic(err)
}
t.columnLookup[c.Name()] = c
}
if len(columns) == 0 {
panic(fmt.Sprintf("Table %s has no columns", name))
}
return t
} | go | func NewTable(name string, columns ...NonAliasColumn) *Table {
if !validIdentifierName(name) {
panic("Invalid table name")
}
t := &Table{
name: name,
columns: columns,
columnLookup: make(map[string]NonAliasColumn),
}
for _, c := range columns {
err := c.setTableName(name)
if err != nil {
panic(err)
}
t.columnLookup[c.Name()] = c
}
if len(columns) == 0 {
panic(fmt.Sprintf("Table %s has no columns", name))
}
return t
} | [
"func",
"NewTable",
"(",
"name",
"string",
",",
"columns",
"...",
"NonAliasColumn",
")",
"*",
"Table",
"{",
"if",
"!",
"validIdentifierName",
"(",
"name",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"t",
":=",
"&",
"Table",
"{",
"name",
":",
"name",
",",
"columns",
":",
"columns",
",",
"columnLookup",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"NonAliasColumn",
")",
",",
"}",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"columns",
"{",
"err",
":=",
"c",
".",
"setTableName",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"t",
".",
"columnLookup",
"[",
"c",
".",
"Name",
"(",
")",
"]",
"=",
"c",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"columns",
")",
"==",
"0",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"\n",
"}",
"\n\n",
"return",
"t",
"\n",
"}"
] | // Defines a physical table in the database that is both readable and writable.
// This function will panic if name is not valid | [
"Defines",
"a",
"physical",
"table",
"in",
"the",
"database",
"that",
"is",
"both",
"readable",
"and",
"writable",
".",
"This",
"function",
"will",
"panic",
"if",
"name",
"is",
"not",
"valid"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L53-L76 | train |
dropbox/godropbox | database/sqlbuilder/table.go | getColumn | func (t *Table) getColumn(name string) (NonAliasColumn, error) {
if c, ok := t.columnLookup[name]; ok {
return c, nil
}
return nil, errors.Newf("No such column '%s' in table '%s'", name, t.name)
} | go | func (t *Table) getColumn(name string) (NonAliasColumn, error) {
if c, ok := t.columnLookup[name]; ok {
return c, nil
}
return nil, errors.Newf("No such column '%s' in table '%s'", name, t.name)
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"getColumn",
"(",
"name",
"string",
")",
"(",
"NonAliasColumn",
",",
"error",
")",
"{",
"if",
"c",
",",
"ok",
":=",
"t",
".",
"columnLookup",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"c",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"name",
",",
"t",
".",
"name",
")",
"\n",
"}"
] | // Returns the specified column, or errors if it doesn't exist in the table | [
"Returns",
"the",
"specified",
"column",
"or",
"errors",
"if",
"it",
"doesn",
"t",
"exist",
"in",
"the",
"table"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L87-L92 | train |
dropbox/godropbox | database/sqlbuilder/table.go | C | func (t *Table) C(name string) NonAliasColumn {
return &deferredLookupColumn{
table: t,
colName: name,
}
} | go | func (t *Table) C(name string) NonAliasColumn {
return &deferredLookupColumn{
table: t,
colName: name,
}
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"C",
"(",
"name",
"string",
")",
"NonAliasColumn",
"{",
"return",
"&",
"deferredLookupColumn",
"{",
"table",
":",
"t",
",",
"colName",
":",
"name",
",",
"}",
"\n",
"}"
] | // Returns a pseudo column representation of the column name. Error checking
// is deferred to SerializeSql. | [
"Returns",
"a",
"pseudo",
"column",
"representation",
"of",
"the",
"column",
"name",
".",
"Error",
"checking",
"is",
"deferred",
"to",
"SerializeSql",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L96-L101 | train |
dropbox/godropbox | database/sqlbuilder/table.go | Projections | func (t *Table) Projections() []Projection {
result := make([]Projection, 0)
for _, col := range t.columns {
result = append(result, col)
}
return result
} | go | func (t *Table) Projections() []Projection {
result := make([]Projection, 0)
for _, col := range t.columns {
result = append(result, col)
}
return result
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"Projections",
"(",
")",
"[",
"]",
"Projection",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"Projection",
",",
"0",
")",
"\n\n",
"for",
"_",
",",
"col",
":=",
"range",
"t",
".",
"columns",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"col",
")",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // Returns all columns for a table as a slice of projections | [
"Returns",
"all",
"columns",
"for",
"a",
"table",
"as",
"a",
"slice",
"of",
"projections"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L104-L112 | train |
dropbox/godropbox | database/sqlbuilder/table.go | ForceIndex | func (t *Table) ForceIndex(index string) *Table {
newTable := *t
newTable.forcedIndex = index
return &newTable
} | go | func (t *Table) ForceIndex(index string) *Table {
newTable := *t
newTable.forcedIndex = index
return &newTable
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"ForceIndex",
"(",
"index",
"string",
")",
"*",
"Table",
"{",
"newTable",
":=",
"*",
"t",
"\n",
"newTable",
".",
"forcedIndex",
"=",
"index",
"\n",
"return",
"&",
"newTable",
"\n",
"}"
] | // Returns a copy of this table, but with the specified index forced. | [
"Returns",
"a",
"copy",
"of",
"this",
"table",
"but",
"with",
"the",
"specified",
"index",
"forced",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L125-L129 | train |
dropbox/godropbox | database/sqlbuilder/table.go | InnerJoinOn | func (t *Table) InnerJoinOn(
table ReadableTable,
onCondition BoolExpression) ReadableTable {
return InnerJoinOn(t, table, onCondition)
} | go | func (t *Table) InnerJoinOn(
table ReadableTable,
onCondition BoolExpression) ReadableTable {
return InnerJoinOn(t, table, onCondition)
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"InnerJoinOn",
"(",
"table",
"ReadableTable",
",",
"onCondition",
"BoolExpression",
")",
"ReadableTable",
"{",
"return",
"InnerJoinOn",
"(",
"t",
",",
"table",
",",
"onCondition",
")",
"\n",
"}"
] | // Creates a inner join table expression using onCondition. | [
"Creates",
"a",
"inner",
"join",
"table",
"expression",
"using",
"onCondition",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L158-L163 | train |
dropbox/godropbox | database/sqlbuilder/table.go | LeftJoinOn | func (t *Table) LeftJoinOn(
table ReadableTable,
onCondition BoolExpression) ReadableTable {
return LeftJoinOn(t, table, onCondition)
} | go | func (t *Table) LeftJoinOn(
table ReadableTable,
onCondition BoolExpression) ReadableTable {
return LeftJoinOn(t, table, onCondition)
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"LeftJoinOn",
"(",
"table",
"ReadableTable",
",",
"onCondition",
"BoolExpression",
")",
"ReadableTable",
"{",
"return",
"LeftJoinOn",
"(",
"t",
",",
"table",
",",
"onCondition",
")",
"\n",
"}"
] | // Creates a left join table expression using onCondition. | [
"Creates",
"a",
"left",
"join",
"table",
"expression",
"using",
"onCondition",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L166-L171 | train |
dropbox/godropbox | database/sqlbuilder/table.go | RightJoinOn | func (t *Table) RightJoinOn(
table ReadableTable,
onCondition BoolExpression) ReadableTable {
return RightJoinOn(t, table, onCondition)
} | go | func (t *Table) RightJoinOn(
table ReadableTable,
onCondition BoolExpression) ReadableTable {
return RightJoinOn(t, table, onCondition)
} | [
"func",
"(",
"t",
"*",
"Table",
")",
"RightJoinOn",
"(",
"table",
"ReadableTable",
",",
"onCondition",
"BoolExpression",
")",
"ReadableTable",
"{",
"return",
"RightJoinOn",
"(",
"t",
",",
"table",
",",
"onCondition",
")",
"\n",
"}"
] | // Creates a right join table expression using onCondition. | [
"Creates",
"a",
"right",
"join",
"table",
"expression",
"using",
"onCondition",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/table.go#L174-L179 | train |
dropbox/godropbox | database/binlog/previous_gtid_log_event.go | Parse | func (p *PreviousGtidsLogEventParser) Parse(raw *RawV4Event) (Event, error) {
pgle := &PreviousGtidsLogEvent{
Event: raw,
set: make(map[string][]GtidRange),
}
data := raw.VariableLengthData()
if len(data) < 8 {
return nil, errors.Newf("Not enough bytes for n_sids: %v", data)
}
nSids, data := LittleEndian.Uint64(data[:8]), data[8:]
for i := uint64(0); i < nSids; i++ {
if len(data) < 16 {
return nil, errors.Newf("Not enough bytes for sid: %v", data)
}
var sid string
sid, data = string(data[:16]), data[16:]
if len(data) < 8 {
return nil, errors.Newf("Not enough bytes for n_intervals: %v", data)
}
var nIntervals uint64
nIntervals, data = LittleEndian.Uint64(data[:8]), data[8:]
for j := uint64(0); j < nIntervals; j++ {
if len(data) < 16 {
return nil, errors.Newf("Not enough bytes for start/end: %v", data)
}
var start, end uint64
start, data = LittleEndian.Uint64(data[:8]), data[8:]
end, data = LittleEndian.Uint64(data[:8]), data[8:]
pgle.set[sid] = append(pgle.set[sid], GtidRange{start, end})
}
}
if len(data) > 0 {
return nil, errors.Newf("Extra bytes at the end: %v", data)
}
return pgle, nil
} | go | func (p *PreviousGtidsLogEventParser) Parse(raw *RawV4Event) (Event, error) {
pgle := &PreviousGtidsLogEvent{
Event: raw,
set: make(map[string][]GtidRange),
}
data := raw.VariableLengthData()
if len(data) < 8 {
return nil, errors.Newf("Not enough bytes for n_sids: %v", data)
}
nSids, data := LittleEndian.Uint64(data[:8]), data[8:]
for i := uint64(0); i < nSids; i++ {
if len(data) < 16 {
return nil, errors.Newf("Not enough bytes for sid: %v", data)
}
var sid string
sid, data = string(data[:16]), data[16:]
if len(data) < 8 {
return nil, errors.Newf("Not enough bytes for n_intervals: %v", data)
}
var nIntervals uint64
nIntervals, data = LittleEndian.Uint64(data[:8]), data[8:]
for j := uint64(0); j < nIntervals; j++ {
if len(data) < 16 {
return nil, errors.Newf("Not enough bytes for start/end: %v", data)
}
var start, end uint64
start, data = LittleEndian.Uint64(data[:8]), data[8:]
end, data = LittleEndian.Uint64(data[:8]), data[8:]
pgle.set[sid] = append(pgle.set[sid], GtidRange{start, end})
}
}
if len(data) > 0 {
return nil, errors.Newf("Extra bytes at the end: %v", data)
}
return pgle, nil
} | [
"func",
"(",
"p",
"*",
"PreviousGtidsLogEventParser",
")",
"Parse",
"(",
"raw",
"*",
"RawV4Event",
")",
"(",
"Event",
",",
"error",
")",
"{",
"pgle",
":=",
"&",
"PreviousGtidsLogEvent",
"{",
"Event",
":",
"raw",
",",
"set",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"GtidRange",
")",
",",
"}",
"\n\n",
"data",
":=",
"raw",
".",
"VariableLengthData",
"(",
")",
"\n",
"if",
"len",
"(",
"data",
")",
"<",
"8",
"{",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"nSids",
",",
"data",
":=",
"LittleEndian",
".",
"Uint64",
"(",
"data",
"[",
":",
"8",
"]",
")",
",",
"data",
"[",
"8",
":",
"]",
"\n",
"for",
"i",
":=",
"uint64",
"(",
"0",
")",
";",
"i",
"<",
"nSids",
";",
"i",
"++",
"{",
"if",
"len",
"(",
"data",
")",
"<",
"16",
"{",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"var",
"sid",
"string",
"\n",
"sid",
",",
"data",
"=",
"string",
"(",
"data",
"[",
":",
"16",
"]",
")",
",",
"data",
"[",
"16",
":",
"]",
"\n",
"if",
"len",
"(",
"data",
")",
"<",
"8",
"{",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"var",
"nIntervals",
"uint64",
"\n",
"nIntervals",
",",
"data",
"=",
"LittleEndian",
".",
"Uint64",
"(",
"data",
"[",
":",
"8",
"]",
")",
",",
"data",
"[",
"8",
":",
"]",
"\n",
"for",
"j",
":=",
"uint64",
"(",
"0",
")",
";",
"j",
"<",
"nIntervals",
";",
"j",
"++",
"{",
"if",
"len",
"(",
"data",
")",
"<",
"16",
"{",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"var",
"start",
",",
"end",
"uint64",
"\n",
"start",
",",
"data",
"=",
"LittleEndian",
".",
"Uint64",
"(",
"data",
"[",
":",
"8",
"]",
")",
",",
"data",
"[",
"8",
":",
"]",
"\n",
"end",
",",
"data",
"=",
"LittleEndian",
".",
"Uint64",
"(",
"data",
"[",
":",
"8",
"]",
")",
",",
"data",
"[",
"8",
":",
"]",
"\n\n",
"pgle",
".",
"set",
"[",
"sid",
"]",
"=",
"append",
"(",
"pgle",
".",
"set",
"[",
"sid",
"]",
",",
"GtidRange",
"{",
"start",
",",
"end",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"data",
")",
">",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"return",
"pgle",
",",
"nil",
"\n",
"}"
] | // PreviousGtidLogEventParser's Parse processes a raw gtid log event into a PreviousGtidLogEvent. | [
"PreviousGtidLogEventParser",
"s",
"Parse",
"processes",
"a",
"raw",
"gtid",
"log",
"event",
"into",
"a",
"PreviousGtidLogEvent",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/previous_gtid_log_event.go#L54-L97 | train |
dropbox/godropbox | encoding2/hex.go | HexEncodeToWriter | func HexEncodeToWriter(w BinaryWriter, data []byte) {
for _, b := range data {
w.Write(hexMap[b])
}
} | go | func HexEncodeToWriter(w BinaryWriter, data []byte) {
for _, b := range data {
w.Write(hexMap[b])
}
} | [
"func",
"HexEncodeToWriter",
"(",
"w",
"BinaryWriter",
",",
"data",
"[",
"]",
"byte",
")",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"data",
"{",
"w",
".",
"Write",
"(",
"hexMap",
"[",
"b",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // This hex encodes the binary data and writes the encoded data to the writer. | [
"This",
"hex",
"encodes",
"the",
"binary",
"data",
"and",
"writes",
"the",
"encoded",
"data",
"to",
"the",
"writer",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/encoding2/hex.go#L10-L14 | train |
dropbox/godropbox | resource_pool/round_robin_resource_pool.go | NewRoundRobinResourcePool | func NewRoundRobinResourcePool(
options Options,
createPool func(Options) ResourcePool,
pools ...*ResourceLocationPool) (ResourcePool, error) {
locations := make(map[string]bool)
for _, pool := range pools {
if pool.ResourceLocation == "" {
return nil, errors.New("Invalid resource location")
}
if locations[pool.ResourceLocation] {
return nil, errors.Newf(
"Duplication resource location %s",
pool.ResourceLocation)
}
locations[pool.ResourceLocation] = true
if pool.Pool == nil {
return nil, errors.New("Invalid pool")
}
}
if createPool == nil {
createPool = NewSimpleResourcePool
}
counter := new(int64)
atomic.StoreInt64(counter, 0)
shuffle(pools)
return &roundRobinResourcePool{
options: options,
createPool: createPool,
rwMutex: sync.RWMutex{},
isLameDuck: false,
pools: pools,
counter: counter,
}, nil
} | go | func NewRoundRobinResourcePool(
options Options,
createPool func(Options) ResourcePool,
pools ...*ResourceLocationPool) (ResourcePool, error) {
locations := make(map[string]bool)
for _, pool := range pools {
if pool.ResourceLocation == "" {
return nil, errors.New("Invalid resource location")
}
if locations[pool.ResourceLocation] {
return nil, errors.Newf(
"Duplication resource location %s",
pool.ResourceLocation)
}
locations[pool.ResourceLocation] = true
if pool.Pool == nil {
return nil, errors.New("Invalid pool")
}
}
if createPool == nil {
createPool = NewSimpleResourcePool
}
counter := new(int64)
atomic.StoreInt64(counter, 0)
shuffle(pools)
return &roundRobinResourcePool{
options: options,
createPool: createPool,
rwMutex: sync.RWMutex{},
isLameDuck: false,
pools: pools,
counter: counter,
}, nil
} | [
"func",
"NewRoundRobinResourcePool",
"(",
"options",
"Options",
",",
"createPool",
"func",
"(",
"Options",
")",
"ResourcePool",
",",
"pools",
"...",
"*",
"ResourceLocationPool",
")",
"(",
"ResourcePool",
",",
"error",
")",
"{",
"locations",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n\n",
"for",
"_",
",",
"pool",
":=",
"range",
"pools",
"{",
"if",
"pool",
".",
"ResourceLocation",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"locations",
"[",
"pool",
".",
"ResourceLocation",
"]",
"{",
"return",
"nil",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"pool",
".",
"ResourceLocation",
")",
"\n",
"}",
"\n",
"locations",
"[",
"pool",
".",
"ResourceLocation",
"]",
"=",
"true",
"\n\n",
"if",
"pool",
".",
"Pool",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"createPool",
"==",
"nil",
"{",
"createPool",
"=",
"NewSimpleResourcePool",
"\n",
"}",
"\n\n",
"counter",
":=",
"new",
"(",
"int64",
")",
"\n",
"atomic",
".",
"StoreInt64",
"(",
"counter",
",",
"0",
")",
"\n\n",
"shuffle",
"(",
"pools",
")",
"\n\n",
"return",
"&",
"roundRobinResourcePool",
"{",
"options",
":",
"options",
",",
"createPool",
":",
"createPool",
",",
"rwMutex",
":",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"isLameDuck",
":",
"false",
",",
"pools",
":",
"pools",
",",
"counter",
":",
"counter",
",",
"}",
",",
"nil",
"\n",
"}"
] | // This returns a RoundRobinResourcePool. | [
"This",
"returns",
"a",
"RoundRobinResourcePool",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/round_robin_resource_pool.go#L38-L79 | train |
dropbox/godropbox | database/binlog/event.go | EventType | func (e *RawV4Event) EventType() mysql_proto.LogEventType_Type {
return mysql_proto.LogEventType_Type(e.header.EventType)
} | go | func (e *RawV4Event) EventType() mysql_proto.LogEventType_Type {
return mysql_proto.LogEventType_Type(e.header.EventType)
} | [
"func",
"(",
"e",
"*",
"RawV4Event",
")",
"EventType",
"(",
")",
"mysql_proto",
".",
"LogEventType_Type",
"{",
"return",
"mysql_proto",
".",
"LogEventType_Type",
"(",
"e",
".",
"header",
".",
"EventType",
")",
"\n",
"}"
] | // EventType returns the event's type. | [
"EventType",
"returns",
"the",
"event",
"s",
"type",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event.go#L108-L110 | train |
dropbox/godropbox | database/binlog/event.go | VariableLengthData | func (e *RawV4Event) VariableLengthData() []byte {
begin := (sizeOfBasicV4EventHeader +
e.extraHeadersSize +
e.fixedLengthDataSize)
end := len(e.data) - e.checksumSize
return e.data[begin:end]
} | go | func (e *RawV4Event) VariableLengthData() []byte {
begin := (sizeOfBasicV4EventHeader +
e.extraHeadersSize +
e.fixedLengthDataSize)
end := len(e.data) - e.checksumSize
return e.data[begin:end]
} | [
"func",
"(",
"e",
"*",
"RawV4Event",
")",
"VariableLengthData",
"(",
")",
"[",
"]",
"byte",
"{",
"begin",
":=",
"(",
"sizeOfBasicV4EventHeader",
"+",
"e",
".",
"extraHeadersSize",
"+",
"e",
".",
"fixedLengthDataSize",
")",
"\n",
"end",
":=",
"len",
"(",
"e",
".",
"data",
")",
"-",
"e",
".",
"checksumSize",
"\n",
"return",
"e",
".",
"data",
"[",
"begin",
":",
"end",
"]",
"\n",
"}"
] | // VariableLengthData returns the variable length data associated to the event.
// By default, the variable length data also include the extra headers, the
// fixed length data and the optional checksum footer. | [
"VariableLengthData",
"returns",
"the",
"variable",
"length",
"data",
"associated",
"to",
"the",
"event",
".",
"By",
"default",
"the",
"variable",
"length",
"data",
"also",
"include",
"the",
"extra",
"headers",
"the",
"fixed",
"length",
"data",
"and",
"the",
"optional",
"checksum",
"footer",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event.go#L167-L173 | train |
dropbox/godropbox | database/binlog/event.go | SetExtraHeadersSize | func (e *RawV4Event) SetExtraHeadersSize(size int) error {
newFixedSize := (size +
sizeOfBasicV4EventHeader +
e.fixedLengthDataSize +
e.checksumSize)
if size < 0 || newFixedSize > len(e.data) {
return errors.Newf(
"Invalid extra headers size (data size: %d basic header size: %d"+
"fixed length data size: %d checksum size: %d input: %d)",
len(e.data),
sizeOfBasicV4EventHeader,
e.fixedLengthDataSize,
e.checksumSize,
size)
}
e.extraHeadersSize = size
return nil
} | go | func (e *RawV4Event) SetExtraHeadersSize(size int) error {
newFixedSize := (size +
sizeOfBasicV4EventHeader +
e.fixedLengthDataSize +
e.checksumSize)
if size < 0 || newFixedSize > len(e.data) {
return errors.Newf(
"Invalid extra headers size (data size: %d basic header size: %d"+
"fixed length data size: %d checksum size: %d input: %d)",
len(e.data),
sizeOfBasicV4EventHeader,
e.fixedLengthDataSize,
e.checksumSize,
size)
}
e.extraHeadersSize = size
return nil
} | [
"func",
"(",
"e",
"*",
"RawV4Event",
")",
"SetExtraHeadersSize",
"(",
"size",
"int",
")",
"error",
"{",
"newFixedSize",
":=",
"(",
"size",
"+",
"sizeOfBasicV4EventHeader",
"+",
"e",
".",
"fixedLengthDataSize",
"+",
"e",
".",
"checksumSize",
")",
"\n",
"if",
"size",
"<",
"0",
"||",
"newFixedSize",
">",
"len",
"(",
"e",
".",
"data",
")",
"{",
"return",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"len",
"(",
"e",
".",
"data",
")",
",",
"sizeOfBasicV4EventHeader",
",",
"e",
".",
"fixedLengthDataSize",
",",
"e",
".",
"checksumSize",
",",
"size",
")",
"\n",
"}",
"\n",
"e",
".",
"extraHeadersSize",
"=",
"size",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set the extra headers' size. | [
"Set",
"the",
"extra",
"headers",
"size",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event.go#L183-L200 | train |
dropbox/godropbox | caching/cache_on_storage.go | NewCacheOnStorage | func NewCacheOnStorage(
cache Storage,
storage Storage) Storage {
return &CacheOnStorage{
cache: cache,
storage: storage,
}
} | go | func NewCacheOnStorage(
cache Storage,
storage Storage) Storage {
return &CacheOnStorage{
cache: cache,
storage: storage,
}
} | [
"func",
"NewCacheOnStorage",
"(",
"cache",
"Storage",
",",
"storage",
"Storage",
")",
"Storage",
"{",
"return",
"&",
"CacheOnStorage",
"{",
"cache",
":",
"cache",
",",
"storage",
":",
"storage",
",",
"}",
"\n",
"}"
] | // This returns a CacheOnStorage, which adds a cache layer on top of the
// storage. | [
"This",
"returns",
"a",
"CacheOnStorage",
"which",
"adds",
"a",
"cache",
"layer",
"on",
"top",
"of",
"the",
"storage",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/caching/cache_on_storage.go#L17-L25 | train |
dropbox/godropbox | cinterop/maximally_batched_work.go | readUntilNullWorkSizeBatch | func readUntilNullWorkSizeBatch(socketRead io.ReadCloser,
batch []byte, workSize int) (size int, err error) {
err = nil
size = 0
if workSize == 0 {
size, err = io.ReadFull(socketRead, batch)
} else {
lastCheckedForNull := 0
for err == nil {
var offset int
offset, err = socketRead.Read(batch[size:])
size += offset
if err == nil && size < len(batch) {
endCheck := size - (size % workSize)
if zeroWorkItem(batch[lastCheckedForNull:endCheck], workSize) {
if size%workSize != 0 {
rem := workSize - (size % workSize)
offset, err = io.ReadFull(socketRead, batch[size:size+rem])
size += offset
}
return
}
lastCheckedForNull = endCheck // need to check partial work items
} else {
return
}
}
}
return
} | go | func readUntilNullWorkSizeBatch(socketRead io.ReadCloser,
batch []byte, workSize int) (size int, err error) {
err = nil
size = 0
if workSize == 0 {
size, err = io.ReadFull(socketRead, batch)
} else {
lastCheckedForNull := 0
for err == nil {
var offset int
offset, err = socketRead.Read(batch[size:])
size += offset
if err == nil && size < len(batch) {
endCheck := size - (size % workSize)
if zeroWorkItem(batch[lastCheckedForNull:endCheck], workSize) {
if size%workSize != 0 {
rem := workSize - (size % workSize)
offset, err = io.ReadFull(socketRead, batch[size:size+rem])
size += offset
}
return
}
lastCheckedForNull = endCheck // need to check partial work items
} else {
return
}
}
}
return
} | [
"func",
"readUntilNullWorkSizeBatch",
"(",
"socketRead",
"io",
".",
"ReadCloser",
",",
"batch",
"[",
"]",
"byte",
",",
"workSize",
"int",
")",
"(",
"size",
"int",
",",
"err",
"error",
")",
"{",
"err",
"=",
"nil",
"\n",
"size",
"=",
"0",
"\n",
"if",
"workSize",
"==",
"0",
"{",
"size",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"socketRead",
",",
"batch",
")",
"\n",
"}",
"else",
"{",
"lastCheckedForNull",
":=",
"0",
"\n",
"for",
"err",
"==",
"nil",
"{",
"var",
"offset",
"int",
"\n",
"offset",
",",
"err",
"=",
"socketRead",
".",
"Read",
"(",
"batch",
"[",
"size",
":",
"]",
")",
"\n",
"size",
"+=",
"offset",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"size",
"<",
"len",
"(",
"batch",
")",
"{",
"endCheck",
":=",
"size",
"-",
"(",
"size",
"%",
"workSize",
")",
"\n",
"if",
"zeroWorkItem",
"(",
"batch",
"[",
"lastCheckedForNull",
":",
"endCheck",
"]",
",",
"workSize",
")",
"{",
"if",
"size",
"%",
"workSize",
"!=",
"0",
"{",
"rem",
":=",
"workSize",
"-",
"(",
"size",
"%",
"workSize",
")",
"\n",
"offset",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"socketRead",
",",
"batch",
"[",
"size",
":",
"size",
"+",
"rem",
"]",
")",
"\n",
"size",
"+=",
"offset",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"lastCheckedForNull",
"=",
"endCheck",
"// need to check partial work items",
"\n",
"}",
"else",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // this reads socketRead to fill up the given buffer unless an error is encountered or
// workSize zeros in a row are discovered, aligned with WorkSize, causing a flush | [
"this",
"reads",
"socketRead",
"to",
"fill",
"up",
"the",
"given",
"buffer",
"unless",
"an",
"error",
"is",
"encountered",
"or",
"workSize",
"zeros",
"in",
"a",
"row",
"are",
"discovered",
"aligned",
"with",
"WorkSize",
"causing",
"a",
"flush"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/maximally_batched_work.go#L30-L59 | train |
dropbox/godropbox | cinterop/maximally_batched_work.go | readBatch | func readBatch(copyTo chan<- []byte, socketRead io.ReadCloser, batchSize int, workSize int) {
defer close(copyTo)
for {
batch := make([]byte, batchSize)
size, err := readUntilNullWorkSizeBatch(socketRead, batch, workSize)
if size > 0 {
if err != nil && workSize != 0 {
size -= (size % workSize)
}
copyTo <- batch[:size]
}
if err != nil {
if err != io.EOF {
log.Print("Error encountered in readBatch:", err)
}
return
}
}
} | go | func readBatch(copyTo chan<- []byte, socketRead io.ReadCloser, batchSize int, workSize int) {
defer close(copyTo)
for {
batch := make([]byte, batchSize)
size, err := readUntilNullWorkSizeBatch(socketRead, batch, workSize)
if size > 0 {
if err != nil && workSize != 0 {
size -= (size % workSize)
}
copyTo <- batch[:size]
}
if err != nil {
if err != io.EOF {
log.Print("Error encountered in readBatch:", err)
}
return
}
}
} | [
"func",
"readBatch",
"(",
"copyTo",
"chan",
"<-",
"[",
"]",
"byte",
",",
"socketRead",
"io",
".",
"ReadCloser",
",",
"batchSize",
"int",
",",
"workSize",
"int",
")",
"{",
"defer",
"close",
"(",
"copyTo",
")",
"\n",
"for",
"{",
"batch",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"batchSize",
")",
"\n",
"size",
",",
"err",
":=",
"readUntilNullWorkSizeBatch",
"(",
"socketRead",
",",
"batch",
",",
"workSize",
")",
"\n",
"if",
"size",
">",
"0",
"{",
"if",
"err",
"!=",
"nil",
"&&",
"workSize",
"!=",
"0",
"{",
"size",
"-=",
"(",
"size",
"%",
"workSize",
")",
"\n",
"}",
"\n",
"copyTo",
"<-",
"batch",
"[",
":",
"size",
"]",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"io",
".",
"EOF",
"{",
"log",
".",
"Print",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // this reads in a loop from socketRead putting batchSize bytes of work to copyTo until
// the socketRead is empty.
// Batches may be shorter than batchSize if a whole workSize element is all zeros
// If workSize of zero is passed in, then the entire batchSize will be filled up regardless,
// unless socketRead returns an error when Read | [
"this",
"reads",
"in",
"a",
"loop",
"from",
"socketRead",
"putting",
"batchSize",
"bytes",
"of",
"work",
"to",
"copyTo",
"until",
"the",
"socketRead",
"is",
"empty",
".",
"Batches",
"may",
"be",
"shorter",
"than",
"batchSize",
"if",
"a",
"whole",
"workSize",
"element",
"is",
"all",
"zeros",
"If",
"workSize",
"of",
"zero",
"is",
"passed",
"in",
"then",
"the",
"entire",
"batchSize",
"will",
"be",
"filled",
"up",
"regardless",
"unless",
"socketRead",
"returns",
"an",
"error",
"when",
"Read"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/cinterop/maximally_batched_work.go#L66-L84 | train |
dropbox/godropbox | time2/mock_clock.go | Advance | func (c *MockClock) Advance(delta time.Duration) {
c.mutex.Lock()
defer c.mutex.Unlock()
end := c.now.Add(delta)
c.advanceTo(end)
} | go | func (c *MockClock) Advance(delta time.Duration) {
c.mutex.Lock()
defer c.mutex.Unlock()
end := c.now.Add(delta)
c.advanceTo(end)
} | [
"func",
"(",
"c",
"*",
"MockClock",
")",
"Advance",
"(",
"delta",
"time",
".",
"Duration",
")",
"{",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"end",
":=",
"c",
".",
"now",
".",
"Add",
"(",
"delta",
")",
"\n",
"c",
".",
"advanceTo",
"(",
"end",
")",
"\n",
"}"
] | // Advances the mock clock by the specified duration. | [
"Advances",
"the",
"mock",
"clock",
"by",
"the",
"specified",
"duration",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/mock_clock.go#L65-L71 | train |
dropbox/godropbox | time2/mock_clock.go | AdvanceTo | func (c *MockClock) AdvanceTo(t time.Time) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.advanceTo(t)
} | go | func (c *MockClock) AdvanceTo(t time.Time) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.advanceTo(t)
} | [
"func",
"(",
"c",
"*",
"MockClock",
")",
"AdvanceTo",
"(",
"t",
"time",
".",
"Time",
")",
"{",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"c",
".",
"advanceTo",
"(",
"t",
")",
"\n",
"}"
] | // Advance to a specific time. | [
"Advance",
"to",
"a",
"specific",
"time",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/mock_clock.go#L74-L79 | train |
dropbox/godropbox | time2/mock_clock.go | Now | func (c *MockClock) Now() time.Time {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.now
} | go | func (c *MockClock) Now() time.Time {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.now
} | [
"func",
"(",
"c",
"*",
"MockClock",
")",
"Now",
"(",
")",
"time",
".",
"Time",
"{",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"c",
".",
"now",
"\n",
"}"
] | // Returns the fake current time. | [
"Returns",
"the",
"fake",
"current",
"time",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/time2/mock_clock.go#L89-L94 | train |
dropbox/godropbox | net2/http2/simple_pool.go | Do | func (pool *SimplePool) Do(req *http.Request) (resp *http.Response, err error) {
conn, err := pool.Get()
if err != nil {
return nil, errors.Wrap(err, err.Error())
}
if pool.params.UseSSL {
req.URL.Scheme = "https"
} else {
req.URL.Scheme = "http"
}
if pool.params.UseRequestHost && req.Host != "" {
req.URL.Host = req.Host
} else {
if pool.params.HostHeader != nil {
req.URL.Host = *pool.params.HostHeader
} else {
req.URL.Host = pool.addr
}
}
if pool.connsLimiter != nil {
now := time.Now()
acquired := pool.connsLimiter.TryAcquire(pool.params.ConnectionAcquireTimeout)
acquiredMs := time.Now().Sub(now).Seconds() * 1000
pool.connAcquireMsSummary.Observe(acquiredMs)
if acquired {
pool.acquiredConnsGauge.Inc()
defer func() {
pool.acquiredConnsGauge.Dec()
pool.connsLimiter.Release()
}()
} else {
return nil, DialError{errors.New(
"Dial Error: Reached maximum active requests for connection pool")}
}
}
resp, err = conn.Do(req)
if err != nil {
if _, ok := err.(DialError); ok {
// do nothing. err is already wrapped.
} else if urlErr, ok := err.(*url.Error); ok {
if urlErr.Err == errFollowRedirectDisabled {
// This is not an actual error
return resp, nil
}
if _, ok := urlErr.Err.(DialError); ok {
err = urlErr.Err
} else {
err = errors.Wrap(err, err.Error())
}
} else {
err = errors.Wrap(err, err.Error())
}
}
return
} | go | func (pool *SimplePool) Do(req *http.Request) (resp *http.Response, err error) {
conn, err := pool.Get()
if err != nil {
return nil, errors.Wrap(err, err.Error())
}
if pool.params.UseSSL {
req.URL.Scheme = "https"
} else {
req.URL.Scheme = "http"
}
if pool.params.UseRequestHost && req.Host != "" {
req.URL.Host = req.Host
} else {
if pool.params.HostHeader != nil {
req.URL.Host = *pool.params.HostHeader
} else {
req.URL.Host = pool.addr
}
}
if pool.connsLimiter != nil {
now := time.Now()
acquired := pool.connsLimiter.TryAcquire(pool.params.ConnectionAcquireTimeout)
acquiredMs := time.Now().Sub(now).Seconds() * 1000
pool.connAcquireMsSummary.Observe(acquiredMs)
if acquired {
pool.acquiredConnsGauge.Inc()
defer func() {
pool.acquiredConnsGauge.Dec()
pool.connsLimiter.Release()
}()
} else {
return nil, DialError{errors.New(
"Dial Error: Reached maximum active requests for connection pool")}
}
}
resp, err = conn.Do(req)
if err != nil {
if _, ok := err.(DialError); ok {
// do nothing. err is already wrapped.
} else if urlErr, ok := err.(*url.Error); ok {
if urlErr.Err == errFollowRedirectDisabled {
// This is not an actual error
return resp, nil
}
if _, ok := urlErr.Err.(DialError); ok {
err = urlErr.Err
} else {
err = errors.Wrap(err, err.Error())
}
} else {
err = errors.Wrap(err, err.Error())
}
}
return
} | [
"func",
"(",
"pool",
"*",
"SimplePool",
")",
"Do",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"pool",
".",
"Get",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"if",
"pool",
".",
"params",
".",
"UseSSL",
"{",
"req",
".",
"URL",
".",
"Scheme",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"req",
".",
"URL",
".",
"Scheme",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"pool",
".",
"params",
".",
"UseRequestHost",
"&&",
"req",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"req",
".",
"URL",
".",
"Host",
"=",
"req",
".",
"Host",
"\n",
"}",
"else",
"{",
"if",
"pool",
".",
"params",
".",
"HostHeader",
"!=",
"nil",
"{",
"req",
".",
"URL",
".",
"Host",
"=",
"*",
"pool",
".",
"params",
".",
"HostHeader",
"\n",
"}",
"else",
"{",
"req",
".",
"URL",
".",
"Host",
"=",
"pool",
".",
"addr",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"pool",
".",
"connsLimiter",
"!=",
"nil",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"acquired",
":=",
"pool",
".",
"connsLimiter",
".",
"TryAcquire",
"(",
"pool",
".",
"params",
".",
"ConnectionAcquireTimeout",
")",
"\n",
"acquiredMs",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"now",
")",
".",
"Seconds",
"(",
")",
"*",
"1000",
"\n",
"pool",
".",
"connAcquireMsSummary",
".",
"Observe",
"(",
"acquiredMs",
")",
"\n",
"if",
"acquired",
"{",
"pool",
".",
"acquiredConnsGauge",
".",
"Inc",
"(",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"pool",
".",
"acquiredConnsGauge",
".",
"Dec",
"(",
")",
"\n",
"pool",
".",
"connsLimiter",
".",
"Release",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"DialError",
"{",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"DialError",
")",
";",
"ok",
"{",
"// do nothing. err is already wrapped.",
"}",
"else",
"if",
"urlErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"url",
".",
"Error",
")",
";",
"ok",
"{",
"if",
"urlErr",
".",
"Err",
"==",
"errFollowRedirectDisabled",
"{",
"// This is not an actual error",
"return",
"resp",
",",
"nil",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"urlErr",
".",
"Err",
".",
"(",
"DialError",
")",
";",
"ok",
"{",
"err",
"=",
"urlErr",
".",
"Err",
"\n",
"}",
"else",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Performs the HTTP request using our HTTP client | [
"Performs",
"the",
"HTTP",
"request",
"using",
"our",
"HTTP",
"client"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/simple_pool.go#L163-L221 | train |
dropbox/godropbox | net2/http2/simple_pool.go | DoWithTimeout | func (pool *SimplePool) DoWithTimeout(req *http.Request,
timeout time.Duration) (resp *http.Response, err error) {
return pool.DoWithParams(req, DoParams{Timeout: timeout})
} | go | func (pool *SimplePool) DoWithTimeout(req *http.Request,
timeout time.Duration) (resp *http.Response, err error) {
return pool.DoWithParams(req, DoParams{Timeout: timeout})
} | [
"func",
"(",
"pool",
"*",
"SimplePool",
")",
"DoWithTimeout",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"return",
"pool",
".",
"DoWithParams",
"(",
"req",
",",
"DoParams",
"{",
"Timeout",
":",
"timeout",
"}",
")",
"\n",
"}"
] | // Set a local timeout the actually cancels the request if we've given up. | [
"Set",
"a",
"local",
"timeout",
"the",
"actually",
"cancels",
"the",
"request",
"if",
"we",
"ve",
"given",
"up",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/simple_pool.go#L241-L244 | train |
dropbox/godropbox | net2/http2/simple_pool.go | GetWithKey | func (pool *SimplePool) GetWithKey(key []byte, limit int) (*http.Client, error) {
return pool.Get()
} | go | func (pool *SimplePool) GetWithKey(key []byte, limit int) (*http.Client, error) {
return pool.Get()
} | [
"func",
"(",
"pool",
"*",
"SimplePool",
")",
"GetWithKey",
"(",
"key",
"[",
"]",
"byte",
",",
"limit",
"int",
")",
"(",
"*",
"http",
".",
"Client",
",",
"error",
")",
"{",
"return",
"pool",
".",
"Get",
"(",
")",
"\n",
"}"
] | // SimplePool doesn't care about the key | [
"SimplePool",
"doesn",
"t",
"care",
"about",
"the",
"key"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/simple_pool.go#L256-L258 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | SetActiveSetSize | func (pool *LoadBalancedPool) SetActiveSetSize(size uint64) {
pool.lock.Lock()
defer pool.lock.Unlock()
pool.activeSetSize = size
} | go | func (pool *LoadBalancedPool) SetActiveSetSize(size uint64) {
pool.lock.Lock()
defer pool.lock.Unlock()
pool.activeSetSize = size
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"SetActiveSetSize",
"(",
"size",
"uint64",
")",
"{",
"pool",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pool",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"pool",
".",
"activeSetSize",
"=",
"size",
"\n",
"}"
] | // For the round robin strategy, sets the number of servers to round-robin
// between. The default is 6. | [
"For",
"the",
"round",
"robin",
"strategy",
"sets",
"the",
"number",
"of",
"servers",
"to",
"round",
"-",
"robin",
"between",
".",
"The",
"default",
"is",
"6",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L137-L141 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | Do | func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error) {
return pool.DoWithTimeout(req, 0)
} | go | func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error) {
return pool.DoWithTimeout(req, 0)
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"Do",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"return",
"pool",
".",
"DoWithTimeout",
"(",
"req",
",",
"0",
")",
"\n",
"}"
] | //
// Pool interface methods
// | [
"Pool",
"interface",
"methods"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L223-L225 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | DoWithTimeout | func (pool *LoadBalancedPool) DoWithTimeout(req *http.Request,
timeout time.Duration) (*http.Response, error) {
return pool.DoWithParams(req, DoParams{Timeout: timeout})
} | go | func (pool *LoadBalancedPool) DoWithTimeout(req *http.Request,
timeout time.Duration) (*http.Response, error) {
return pool.DoWithParams(req, DoParams{Timeout: timeout})
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"DoWithTimeout",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"pool",
".",
"DoWithParams",
"(",
"req",
",",
"DoParams",
"{",
"Timeout",
":",
"timeout",
"}",
")",
"\n",
"}"
] | // Issues an HTTP request, distributing more load to relatively unloaded instances. | [
"Issues",
"an",
"HTTP",
"request",
"distributing",
"more",
"load",
"to",
"relatively",
"unloaded",
"instances",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L288-L291 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | getInstance | func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) (
idx int,
instance *instancePool,
isDown bool,
err error) {
pool.lock.RLock()
defer pool.lock.RUnlock()
if len(pool.instanceList) == 0 {
return 0, nil, false, errors.Newf("no available instances")
}
now := time.Now().Unix()
numInstancesToTry := uint64(len(pool.instanceList))
start := 0
// map used to implement soft swapping to avoid picking the same instance multiple times
// when we randomly pick instances for consistent-hashing. We could have used this actually
// for the other strategies.
// TODO(bashar): get rid of the random shuffle for the other strategies
var idxMap map[int]int
if pool.strategy == LBRoundRobin &&
pool.activeSetSize < numInstancesToTry {
numInstancesToTry = pool.activeSetSize
} else if pool.strategy == LBConsistentHashing {
// we must have a key
if len(key) == 0 {
return 0, nil, false, errors.Newf("key was not specified for consistent-hashing")
} else if maxInstances <= 0 {
return 0, nil, false, errors.Newf(
"invalid maxInstances for consistent-hashing: %v", maxInstances)
}
// in case we're asked to try more than the number of servers we have
if maxInstances > int(numInstancesToTry) {
maxInstances = int(numInstancesToTry)
}
// let's find the closest server to start. We don't start from 0 in that case
hash := pool.hashFunction(key, pool.hashSeed)
// we need to find the closest server that hashes to >= hash.
start = sort.Search(len(pool.instanceList), func(i int) bool {
return pool.instanceHashes[i] >= hash
})
// In the case where hash > all elements, sort.Search returns len(pool.instanceList).
// Hence, we mod the result
start = start % len(pool.instanceHashes)
idxMap = make(map[int]int)
}
for i := 0; uint64(i) < numInstancesToTry; i++ {
switch pool.strategy {
case LBRoundRobin:
// In RoundRobin strategy instanceIdx keeps changing, to
// achieve round robin load balancing.
instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1)
idx = int(instanceIdx % numInstancesToTry)
case LBSortedFixed:
// In SortedFixed strategy instances are always traversed in same
// exact order.
idx = i
case LBShuffledFixed:
// In ShuffledFixed strategy instances are also always traversed in
// same exact order.
idx = i
case LBConsistentHashing:
// In ConsistentHashing strategy instances are picked up randomly between
// start and start + numInstancesToTry. This is to load balance between
// the alive servers that are closest to the key in the hash space
// consistent-hashing will prefer availability over consistency. In the case some
// server is down, we will try new servers in the hash-ring. The way we do this is by
// picking random instances next (excluding already picked instances). That's why we
// do a 'soft-swap' between already picked instance and move the start offset by 1
// every time. We don't touch the pool.instanceList to make sure we don't
// screw up any order. The swap below guarantees that start always has an idx that
// has never been tried before.
newStart := i + start
idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList)
// we need to swap idxMap[newStart] with idxMap[idx] (or fill them).
var ok bool
if idxMap[idx], ok = idxMap[idx]; ok {
idxMap[newStart] = idxMap[idx]
} else {
idxMap[newStart] = idx
}
idxMap[idx] = newStart
// we need to pick the correct idx after the swap
idx = idxMap[newStart]
}
if pool.markDownUntil[idx] < now {
break
}
}
return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil
} | go | func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) (
idx int,
instance *instancePool,
isDown bool,
err error) {
pool.lock.RLock()
defer pool.lock.RUnlock()
if len(pool.instanceList) == 0 {
return 0, nil, false, errors.Newf("no available instances")
}
now := time.Now().Unix()
numInstancesToTry := uint64(len(pool.instanceList))
start := 0
// map used to implement soft swapping to avoid picking the same instance multiple times
// when we randomly pick instances for consistent-hashing. We could have used this actually
// for the other strategies.
// TODO(bashar): get rid of the random shuffle for the other strategies
var idxMap map[int]int
if pool.strategy == LBRoundRobin &&
pool.activeSetSize < numInstancesToTry {
numInstancesToTry = pool.activeSetSize
} else if pool.strategy == LBConsistentHashing {
// we must have a key
if len(key) == 0 {
return 0, nil, false, errors.Newf("key was not specified for consistent-hashing")
} else if maxInstances <= 0 {
return 0, nil, false, errors.Newf(
"invalid maxInstances for consistent-hashing: %v", maxInstances)
}
// in case we're asked to try more than the number of servers we have
if maxInstances > int(numInstancesToTry) {
maxInstances = int(numInstancesToTry)
}
// let's find the closest server to start. We don't start from 0 in that case
hash := pool.hashFunction(key, pool.hashSeed)
// we need to find the closest server that hashes to >= hash.
start = sort.Search(len(pool.instanceList), func(i int) bool {
return pool.instanceHashes[i] >= hash
})
// In the case where hash > all elements, sort.Search returns len(pool.instanceList).
// Hence, we mod the result
start = start % len(pool.instanceHashes)
idxMap = make(map[int]int)
}
for i := 0; uint64(i) < numInstancesToTry; i++ {
switch pool.strategy {
case LBRoundRobin:
// In RoundRobin strategy instanceIdx keeps changing, to
// achieve round robin load balancing.
instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1)
idx = int(instanceIdx % numInstancesToTry)
case LBSortedFixed:
// In SortedFixed strategy instances are always traversed in same
// exact order.
idx = i
case LBShuffledFixed:
// In ShuffledFixed strategy instances are also always traversed in
// same exact order.
idx = i
case LBConsistentHashing:
// In ConsistentHashing strategy instances are picked up randomly between
// start and start + numInstancesToTry. This is to load balance between
// the alive servers that are closest to the key in the hash space
// consistent-hashing will prefer availability over consistency. In the case some
// server is down, we will try new servers in the hash-ring. The way we do this is by
// picking random instances next (excluding already picked instances). That's why we
// do a 'soft-swap' between already picked instance and move the start offset by 1
// every time. We don't touch the pool.instanceList to make sure we don't
// screw up any order. The swap below guarantees that start always has an idx that
// has never been tried before.
newStart := i + start
idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList)
// we need to swap idxMap[newStart] with idxMap[idx] (or fill them).
var ok bool
if idxMap[idx], ok = idxMap[idx]; ok {
idxMap[newStart] = idxMap[idx]
} else {
idxMap[newStart] = idx
}
idxMap[idx] = newStart
// we need to pick the correct idx after the swap
idx = idxMap[newStart]
}
if pool.markDownUntil[idx] < now {
break
}
}
return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"getInstance",
"(",
"key",
"[",
"]",
"byte",
",",
"maxInstances",
"int",
")",
"(",
"idx",
"int",
",",
"instance",
"*",
"instancePool",
",",
"isDown",
"bool",
",",
"err",
"error",
")",
"{",
"pool",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"pool",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"pool",
".",
"instanceList",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
",",
"false",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"numInstancesToTry",
":=",
"uint64",
"(",
"len",
"(",
"pool",
".",
"instanceList",
")",
")",
"\n\n",
"start",
":=",
"0",
"\n",
"// map used to implement soft swapping to avoid picking the same instance multiple times",
"// when we randomly pick instances for consistent-hashing. We could have used this actually",
"// for the other strategies.",
"// TODO(bashar): get rid of the random shuffle for the other strategies",
"var",
"idxMap",
"map",
"[",
"int",
"]",
"int",
"\n\n",
"if",
"pool",
".",
"strategy",
"==",
"LBRoundRobin",
"&&",
"pool",
".",
"activeSetSize",
"<",
"numInstancesToTry",
"{",
"numInstancesToTry",
"=",
"pool",
".",
"activeSetSize",
"\n",
"}",
"else",
"if",
"pool",
".",
"strategy",
"==",
"LBConsistentHashing",
"{",
"// we must have a key",
"if",
"len",
"(",
"key",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
",",
"false",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"maxInstances",
"<=",
"0",
"{",
"return",
"0",
",",
"nil",
",",
"false",
",",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
",",
"maxInstances",
")",
"\n",
"}",
"\n\n",
"// in case we're asked to try more than the number of servers we have",
"if",
"maxInstances",
">",
"int",
"(",
"numInstancesToTry",
")",
"{",
"maxInstances",
"=",
"int",
"(",
"numInstancesToTry",
")",
"\n",
"}",
"\n\n",
"// let's find the closest server to start. We don't start from 0 in that case",
"hash",
":=",
"pool",
".",
"hashFunction",
"(",
"key",
",",
"pool",
".",
"hashSeed",
")",
"\n",
"// we need to find the closest server that hashes to >= hash.",
"start",
"=",
"sort",
".",
"Search",
"(",
"len",
"(",
"pool",
".",
"instanceList",
")",
",",
"func",
"(",
"i",
"int",
")",
"bool",
"{",
"return",
"pool",
".",
"instanceHashes",
"[",
"i",
"]",
">=",
"hash",
"\n",
"}",
")",
"\n\n",
"// In the case where hash > all elements, sort.Search returns len(pool.instanceList).",
"// Hence, we mod the result",
"start",
"=",
"start",
"%",
"len",
"(",
"pool",
".",
"instanceHashes",
")",
"\n\n",
"idxMap",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"int",
")",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"uint64",
"(",
"i",
")",
"<",
"numInstancesToTry",
";",
"i",
"++",
"{",
"switch",
"pool",
".",
"strategy",
"{",
"case",
"LBRoundRobin",
":",
"// In RoundRobin strategy instanceIdx keeps changing, to",
"// achieve round robin load balancing.",
"instanceIdx",
":=",
"atomic",
".",
"AddUint64",
"(",
"&",
"pool",
".",
"instanceIdx",
",",
"1",
")",
"\n",
"idx",
"=",
"int",
"(",
"instanceIdx",
"%",
"numInstancesToTry",
")",
"\n",
"case",
"LBSortedFixed",
":",
"// In SortedFixed strategy instances are always traversed in same",
"// exact order.",
"idx",
"=",
"i",
"\n",
"case",
"LBShuffledFixed",
":",
"// In ShuffledFixed strategy instances are also always traversed in",
"// same exact order.",
"idx",
"=",
"i",
"\n",
"case",
"LBConsistentHashing",
":",
"// In ConsistentHashing strategy instances are picked up randomly between",
"// start and start + numInstancesToTry. This is to load balance between",
"// the alive servers that are closest to the key in the hash space",
"// consistent-hashing will prefer availability over consistency. In the case some",
"// server is down, we will try new servers in the hash-ring. The way we do this is by",
"// picking random instances next (excluding already picked instances). That's why we",
"// do a 'soft-swap' between already picked instance and move the start offset by 1",
"// every time. We don't touch the pool.instanceList to make sure we don't",
"// screw up any order. The swap below guarantees that start always has an idx that",
"// has never been tried before.",
"newStart",
":=",
"i",
"+",
"start",
"\n",
"idx",
"=",
"(",
"newStart",
"+",
"rand2",
".",
"Intn",
"(",
"maxInstances",
")",
")",
"%",
"len",
"(",
"pool",
".",
"instanceList",
")",
"\n",
"// we need to swap idxMap[newStart] with idxMap[idx] (or fill them).",
"var",
"ok",
"bool",
"\n",
"if",
"idxMap",
"[",
"idx",
"]",
",",
"ok",
"=",
"idxMap",
"[",
"idx",
"]",
";",
"ok",
"{",
"idxMap",
"[",
"newStart",
"]",
"=",
"idxMap",
"[",
"idx",
"]",
"\n",
"}",
"else",
"{",
"idxMap",
"[",
"newStart",
"]",
"=",
"idx",
"\n",
"}",
"\n",
"idxMap",
"[",
"idx",
"]",
"=",
"newStart",
"\n\n",
"// we need to pick the correct idx after the swap",
"idx",
"=",
"idxMap",
"[",
"newStart",
"]",
"\n",
"}",
"\n\n",
"if",
"pool",
".",
"markDownUntil",
"[",
"idx",
"]",
"<",
"now",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"idx",
",",
"pool",
".",
"instanceList",
"[",
"idx",
"]",
",",
"(",
"pool",
".",
"markDownUntil",
"[",
"idx",
"]",
">=",
"now",
")",
",",
"nil",
"\n",
"}"
] | // Returns instance that isn't marked down, if all instances are
// marked as down it will just choose a next one. | [
"Returns",
"instance",
"that",
"isn",
"t",
"marked",
"down",
"if",
"all",
"instances",
"are",
"marked",
"as",
"down",
"it",
"will",
"just",
"choose",
"a",
"next",
"one",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L312-L412 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | GetSingleInstance | func (pool *LoadBalancedPool) GetSingleInstance() (Pool, error) {
_, instance, _, err := pool.getInstance(nil, 1)
return instance, err
} | go | func (pool *LoadBalancedPool) GetSingleInstance() (Pool, error) {
_, instance, _, err := pool.getInstance(nil, 1)
return instance, err
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"GetSingleInstance",
"(",
")",
"(",
"Pool",
",",
"error",
")",
"{",
"_",
",",
"instance",
",",
"_",
",",
"err",
":=",
"pool",
".",
"getInstance",
"(",
"nil",
",",
"1",
")",
"\n",
"return",
"instance",
",",
"err",
"\n",
"}"
] | // Returns a Pool for an instance selected based on load balancing strategy. | [
"Returns",
"a",
"Pool",
"for",
"an",
"instance",
"selected",
"based",
"on",
"load",
"balancing",
"strategy",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L415-L418 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | markInstanceDown | func (pool *LoadBalancedPool) markInstanceDown(
idx int, instance *instancePool, downUntil int64) {
pool.lock.Lock()
defer pool.lock.Unlock()
if idx < len(pool.instanceList) && pool.instanceList[idx] == instance {
pool.markDownUntil[idx] = downUntil
}
} | go | func (pool *LoadBalancedPool) markInstanceDown(
idx int, instance *instancePool, downUntil int64) {
pool.lock.Lock()
defer pool.lock.Unlock()
if idx < len(pool.instanceList) && pool.instanceList[idx] == instance {
pool.markDownUntil[idx] = downUntil
}
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"markInstanceDown",
"(",
"idx",
"int",
",",
"instance",
"*",
"instancePool",
",",
"downUntil",
"int64",
")",
"{",
"pool",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pool",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"idx",
"<",
"len",
"(",
"pool",
".",
"instanceList",
")",
"&&",
"pool",
".",
"instanceList",
"[",
"idx",
"]",
"==",
"instance",
"{",
"pool",
".",
"markDownUntil",
"[",
"idx",
"]",
"=",
"downUntil",
"\n",
"}",
"\n",
"}"
] | // Marks instance down till downUntil epoch in seconds. | [
"Marks",
"instance",
"down",
"till",
"downUntil",
"epoch",
"in",
"seconds",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L441-L448 | train |
dropbox/godropbox | net2/http2/load_balanced_pool.go | markInstanceUp | func (pool *LoadBalancedPool) markInstanceUp(
idx int, instance *instancePool) {
pool.markInstanceDown(idx, instance, 0)
} | go | func (pool *LoadBalancedPool) markInstanceUp(
idx int, instance *instancePool) {
pool.markInstanceDown(idx, instance, 0)
} | [
"func",
"(",
"pool",
"*",
"LoadBalancedPool",
")",
"markInstanceUp",
"(",
"idx",
"int",
",",
"instance",
"*",
"instancePool",
")",
"{",
"pool",
".",
"markInstanceDown",
"(",
"idx",
",",
"instance",
",",
"0",
")",
"\n",
"}"
] | // Marks instance as ready to be used. | [
"Marks",
"instance",
"as",
"ready",
"to",
"be",
"used",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L451-L454 | train |
dropbox/godropbox | lockstore/map.go | NewLockingMap | func NewLockingMap(options LockingMapOptions) LockingMap {
return &lockingMap{
lock: &sync.RWMutex{},
keyLocker: New(options.LockStoreOptions),
data: make(map[string]interface{}),
checkFunc: options.ValueCheckFunc,
}
} | go | func NewLockingMap(options LockingMapOptions) LockingMap {
return &lockingMap{
lock: &sync.RWMutex{},
keyLocker: New(options.LockStoreOptions),
data: make(map[string]interface{}),
checkFunc: options.ValueCheckFunc,
}
} | [
"func",
"NewLockingMap",
"(",
"options",
"LockingMapOptions",
")",
"LockingMap",
"{",
"return",
"&",
"lockingMap",
"{",
"lock",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"keyLocker",
":",
"New",
"(",
"options",
".",
"LockStoreOptions",
")",
",",
"data",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"checkFunc",
":",
"options",
".",
"ValueCheckFunc",
",",
"}",
"\n",
"}"
] | // NewLockingMap returns a new instance of LockingMap | [
"NewLockingMap",
"returns",
"a",
"new",
"instance",
"of",
"LockingMap"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L71-L78 | train |
dropbox/godropbox | lockstore/map.go | Get | func (m *lockingMap) Get(key string) (interface{}, bool) {
m.keyLocker.RLock(key)
defer m.keyLocker.RUnlock(key)
m.lock.RLock()
defer m.lock.RUnlock()
val, ok := m.data[key]
if ok && (m.checkFunc == nil || m.checkFunc(key, val)) {
return val, true
} else {
// No value or it failed to check
return nil, false
}
} | go | func (m *lockingMap) Get(key string) (interface{}, bool) {
m.keyLocker.RLock(key)
defer m.keyLocker.RUnlock(key)
m.lock.RLock()
defer m.lock.RUnlock()
val, ok := m.data[key]
if ok && (m.checkFunc == nil || m.checkFunc(key, val)) {
return val, true
} else {
// No value or it failed to check
return nil, false
}
} | [
"func",
"(",
"m",
"*",
"lockingMap",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
")",
"{",
"m",
".",
"keyLocker",
".",
"RLock",
"(",
"key",
")",
"\n",
"defer",
"m",
".",
"keyLocker",
".",
"RUnlock",
"(",
"key",
")",
"\n\n",
"m",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"val",
",",
"ok",
":=",
"m",
".",
"data",
"[",
"key",
"]",
"\n",
"if",
"ok",
"&&",
"(",
"m",
".",
"checkFunc",
"==",
"nil",
"||",
"m",
".",
"checkFunc",
"(",
"key",
",",
"val",
")",
")",
"{",
"return",
"val",
",",
"true",
"\n",
"}",
"else",
"{",
"// No value or it failed to check",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"}"
] | // Get returns the value, ok for a given key from within the map. If a ValueCheckFunc
// was defined for the map, the value is only returned if that function returns true. | [
"Get",
"returns",
"the",
"value",
"ok",
"for",
"a",
"given",
"key",
"from",
"within",
"the",
"map",
".",
"If",
"a",
"ValueCheckFunc",
"was",
"defined",
"for",
"the",
"map",
"the",
"value",
"is",
"only",
"returned",
"if",
"that",
"function",
"returns",
"true",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L82-L96 | train |
dropbox/godropbox | lockstore/map.go | Delete | func (m *lockingMap) Delete(key string) {
m.keyLocker.Lock(key)
defer m.keyLocker.Unlock(key)
m.lock.Lock()
defer m.lock.Unlock()
delete(m.data, key)
} | go | func (m *lockingMap) Delete(key string) {
m.keyLocker.Lock(key)
defer m.keyLocker.Unlock(key)
m.lock.Lock()
defer m.lock.Unlock()
delete(m.data, key)
} | [
"func",
"(",
"m",
"*",
"lockingMap",
")",
"Delete",
"(",
"key",
"string",
")",
"{",
"m",
".",
"keyLocker",
".",
"Lock",
"(",
"key",
")",
"\n",
"defer",
"m",
".",
"keyLocker",
".",
"Unlock",
"(",
"key",
")",
"\n\n",
"m",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"delete",
"(",
"m",
".",
"data",
",",
"key",
")",
"\n",
"}"
] | // Delete removes a key from the map if it exists. Returns nothing. | [
"Delete",
"removes",
"a",
"key",
"from",
"the",
"map",
"if",
"it",
"exists",
".",
"Returns",
"nothing",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L99-L107 | train |
dropbox/godropbox | net2/managed_connection.go | NewManagedConn | func NewManagedConn(
network string,
address string,
handle resource_pool.ManagedHandle,
pool ConnectionPool,
options ConnectionOptions) ManagedConn {
addr := NetworkAddress{
Network: network,
Address: address,
}
return &managedConnImpl{
addr: addr,
handle: handle,
pool: pool,
options: options,
}
} | go | func NewManagedConn(
network string,
address string,
handle resource_pool.ManagedHandle,
pool ConnectionPool,
options ConnectionOptions) ManagedConn {
addr := NetworkAddress{
Network: network,
Address: address,
}
return &managedConnImpl{
addr: addr,
handle: handle,
pool: pool,
options: options,
}
} | [
"func",
"NewManagedConn",
"(",
"network",
"string",
",",
"address",
"string",
",",
"handle",
"resource_pool",
".",
"ManagedHandle",
",",
"pool",
"ConnectionPool",
",",
"options",
"ConnectionOptions",
")",
"ManagedConn",
"{",
"addr",
":=",
"NetworkAddress",
"{",
"Network",
":",
"network",
",",
"Address",
":",
"address",
",",
"}",
"\n\n",
"return",
"&",
"managedConnImpl",
"{",
"addr",
":",
"addr",
",",
"handle",
":",
"handle",
",",
"pool",
":",
"pool",
",",
"options",
":",
"options",
",",
"}",
"\n",
"}"
] | // This creates a managed connection wrapper. | [
"This",
"creates",
"a",
"managed",
"connection",
"wrapper",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L51-L69 | train |
dropbox/godropbox | net2/managed_connection.go | RawConn | func (c *managedConnImpl) RawConn() net.Conn {
h, _ := c.handle.Handle()
return h.(net.Conn)
} | go | func (c *managedConnImpl) RawConn() net.Conn {
h, _ := c.handle.Handle()
return h.(net.Conn)
} | [
"func",
"(",
"c",
"*",
"managedConnImpl",
")",
"RawConn",
"(",
")",
"net",
".",
"Conn",
"{",
"h",
",",
"_",
":=",
"c",
".",
"handle",
".",
"Handle",
"(",
")",
"\n",
"return",
"h",
".",
"(",
"net",
".",
"Conn",
")",
"\n",
"}"
] | // See ManagedConn for documentation. | [
"See",
"ManagedConn",
"for",
"documentation",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L77-L80 | train |
dropbox/godropbox | net2/port.go | GetPort | func GetPort(addr net.Addr) (int, error) {
_, lport, err := net.SplitHostPort(addr.String())
if err != nil {
return -1, err
}
lportInt, err := strconv.Atoi(lport)
if err != nil {
return -1, err
}
return lportInt, nil
} | go | func GetPort(addr net.Addr) (int, error) {
_, lport, err := net.SplitHostPort(addr.String())
if err != nil {
return -1, err
}
lportInt, err := strconv.Atoi(lport)
if err != nil {
return -1, err
}
return lportInt, nil
} | [
"func",
"GetPort",
"(",
"addr",
"net",
".",
"Addr",
")",
"(",
"int",
",",
"error",
")",
"{",
"_",
",",
"lport",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"lportInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"lport",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"return",
"lportInt",
",",
"nil",
"\n",
"}"
] | // Returns the port information. | [
"Returns",
"the",
"port",
"information",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/port.go#L9-L19 | train |
dropbox/godropbox | math2/rand2/rand.go | NewSource | func NewSource(seed int64) rand.Source {
return &lockedSource{
src: rand.NewSource(seed),
}
} | go | func NewSource(seed int64) rand.Source {
return &lockedSource{
src: rand.NewSource(seed),
}
} | [
"func",
"NewSource",
"(",
"seed",
"int64",
")",
"rand",
".",
"Source",
"{",
"return",
"&",
"lockedSource",
"{",
"src",
":",
"rand",
".",
"NewSource",
"(",
"seed",
")",
",",
"}",
"\n",
"}"
] | // This returns a thread-safe random source. | [
"This",
"returns",
"a",
"thread",
"-",
"safe",
"random",
"source",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L37-L41 | train |
dropbox/godropbox | math2/rand2/rand.go | GetSeed | func GetSeed() int64 {
now := time.Now()
return now.Unix() + int64(now.Nanosecond()) + 12345*int64(os.Getpid())
} | go | func GetSeed() int64 {
now := time.Now()
return now.Unix() + int64(now.Nanosecond()) + 12345*int64(os.Getpid())
} | [
"func",
"GetSeed",
"(",
")",
"int64",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"return",
"now",
".",
"Unix",
"(",
")",
"+",
"int64",
"(",
"now",
".",
"Nanosecond",
"(",
")",
")",
"+",
"12345",
"*",
"int64",
"(",
"os",
".",
"Getpid",
"(",
")",
")",
"\n",
"}"
] | // Generates a seed based on the current time and the process ID. | [
"Generates",
"a",
"seed",
"based",
"on",
"the",
"current",
"time",
"and",
"the",
"process",
"ID",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L44-L47 | train |
dropbox/godropbox | math2/rand2/rand.go | Dur | func Dur(max time.Duration) time.Duration {
return time.Duration(Int63n(int64(max)))
} | go | func Dur(max time.Duration) time.Duration {
return time.Duration(Int63n(int64(max)))
} | [
"func",
"Dur",
"(",
"max",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"Int63n",
"(",
"int64",
"(",
"max",
")",
")",
")",
"\n",
"}"
] | // Dur returns a pseudo-random Duration in [0, max) | [
"Dur",
"returns",
"a",
"pseudo",
"-",
"random",
"Duration",
"in",
"[",
"0",
"max",
")"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L101-L103 | train |
dropbox/godropbox | math2/rand2/rand.go | SampleInts | func SampleInts(n int, k int) (res []int, err error) {
if k < 0 {
err = errors.Newf("invalid sample size k")
return
}
if n < k {
err = errors.Newf("sample size k larger than n")
return
}
picked := set.NewSet()
for picked.Len() < k {
i := Intn(n)
picked.Add(i)
}
res = make([]int, k)
e := 0
for i := range picked.Iter() {
res[e] = i.(int)
e++
}
return
} | go | func SampleInts(n int, k int) (res []int, err error) {
if k < 0 {
err = errors.Newf("invalid sample size k")
return
}
if n < k {
err = errors.Newf("sample size k larger than n")
return
}
picked := set.NewSet()
for picked.Len() < k {
i := Intn(n)
picked.Add(i)
}
res = make([]int, k)
e := 0
for i := range picked.Iter() {
res[e] = i.(int)
e++
}
return
} | [
"func",
"SampleInts",
"(",
"n",
"int",
",",
"k",
"int",
")",
"(",
"res",
"[",
"]",
"int",
",",
"err",
"error",
")",
"{",
"if",
"k",
"<",
"0",
"{",
"err",
"=",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"n",
"<",
"k",
"{",
"err",
"=",
"errors",
".",
"Newf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"picked",
":=",
"set",
".",
"NewSet",
"(",
")",
"\n",
"for",
"picked",
".",
"Len",
"(",
")",
"<",
"k",
"{",
"i",
":=",
"Intn",
"(",
"n",
")",
"\n",
"picked",
".",
"Add",
"(",
"i",
")",
"\n",
"}",
"\n\n",
"res",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"k",
")",
"\n",
"e",
":=",
"0",
"\n",
"for",
"i",
":=",
"range",
"picked",
".",
"Iter",
"(",
")",
"{",
"res",
"[",
"e",
"]",
"=",
"i",
".",
"(",
"int",
")",
"\n",
"e",
"++",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Samples 'k' unique ints from the range [0, n) | [
"Samples",
"k",
"unique",
"ints",
"from",
"the",
"range",
"[",
"0",
"n",
")"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L118-L143 | train |
dropbox/godropbox | math2/rand2/rand.go | Sample | func Sample(population []interface{}, k int) (res []interface{}, err error) {
n := len(population)
idxs, err := SampleInts(n, k)
if err != nil {
return
}
res = []interface{}{}
for _, idx := range idxs {
res = append(res, population[idx])
}
return
} | go | func Sample(population []interface{}, k int) (res []interface{}, err error) {
n := len(population)
idxs, err := SampleInts(n, k)
if err != nil {
return
}
res = []interface{}{}
for _, idx := range idxs {
res = append(res, population[idx])
}
return
} | [
"func",
"Sample",
"(",
"population",
"[",
"]",
"interface",
"{",
"}",
",",
"k",
"int",
")",
"(",
"res",
"[",
"]",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"n",
":=",
"len",
"(",
"population",
")",
"\n",
"idxs",
",",
"err",
":=",
"SampleInts",
"(",
"n",
",",
"k",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"res",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"_",
",",
"idx",
":=",
"range",
"idxs",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"population",
"[",
"idx",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Samples 'k' elements from the given slice | [
"Samples",
"k",
"elements",
"from",
"the",
"given",
"slice"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L146-L159 | train |
dropbox/godropbox | math2/rand2/rand.go | PickN | func PickN(population []interface{}, n int) (
picked []interface{}, remaining []interface{}, err error) {
total := len(population)
idxs, err := SampleInts(total, n)
if err != nil {
return
}
sort.Ints(idxs)
picked, remaining = []interface{}{}, []interface{}{}
for x, elem := range population {
if len(idxs) > 0 && x == idxs[0] {
picked = append(picked, elem)
idxs = idxs[1:]
} else {
remaining = append(remaining, elem)
}
}
return
} | go | func PickN(population []interface{}, n int) (
picked []interface{}, remaining []interface{}, err error) {
total := len(population)
idxs, err := SampleInts(total, n)
if err != nil {
return
}
sort.Ints(idxs)
picked, remaining = []interface{}{}, []interface{}{}
for x, elem := range population {
if len(idxs) > 0 && x == idxs[0] {
picked = append(picked, elem)
idxs = idxs[1:]
} else {
remaining = append(remaining, elem)
}
}
return
} | [
"func",
"PickN",
"(",
"population",
"[",
"]",
"interface",
"{",
"}",
",",
"n",
"int",
")",
"(",
"picked",
"[",
"]",
"interface",
"{",
"}",
",",
"remaining",
"[",
"]",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"total",
":=",
"len",
"(",
"population",
")",
"\n",
"idxs",
",",
"err",
":=",
"SampleInts",
"(",
"total",
",",
"n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"sort",
".",
"Ints",
"(",
"idxs",
")",
"\n\n",
"picked",
",",
"remaining",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"x",
",",
"elem",
":=",
"range",
"population",
"{",
"if",
"len",
"(",
"idxs",
")",
">",
"0",
"&&",
"x",
"==",
"idxs",
"[",
"0",
"]",
"{",
"picked",
"=",
"append",
"(",
"picked",
",",
"elem",
")",
"\n",
"idxs",
"=",
"idxs",
"[",
"1",
":",
"]",
"\n",
"}",
"else",
"{",
"remaining",
"=",
"append",
"(",
"remaining",
",",
"elem",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Same as 'Sample' except it returns both the 'picked' sample set and the
// 'remaining' elements. | [
"Same",
"as",
"Sample",
"except",
"it",
"returns",
"both",
"the",
"picked",
"sample",
"set",
"and",
"the",
"remaining",
"elements",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L163-L184 | train |
dropbox/godropbox | math2/rand2/rand.go | Shuffle | func Shuffle(collection Swapper) {
// Fisher-Yates shuffle.
for i := collection.Len() - 1; i >= 0; i-- {
collection.Swap(i, Intn(i+1))
}
} | go | func Shuffle(collection Swapper) {
// Fisher-Yates shuffle.
for i := collection.Len() - 1; i >= 0; i-- {
collection.Swap(i, Intn(i+1))
}
} | [
"func",
"Shuffle",
"(",
"collection",
"Swapper",
")",
"{",
"// Fisher-Yates shuffle.",
"for",
"i",
":=",
"collection",
".",
"Len",
"(",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"collection",
".",
"Swap",
"(",
"i",
",",
"Intn",
"(",
"i",
"+",
"1",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Randomly shuffles the collection in place. | [
"Randomly",
"shuffles",
"the",
"collection",
"in",
"place",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L195-L200 | train |
dropbox/godropbox | sync2/semaphore.go | TryAcquire | func (sem *boundedSemaphore) TryAcquire(timeout time.Duration) bool {
if timeout > 0 {
// Wait until we get a slot or timeout expires.
tm := time.NewTimer(timeout)
defer tm.Stop()
select {
case <-sem.slots:
return true
case <-tm.C:
// Timeout expired. In very rare cases this might happen even if
// there is a slot available, e.g. GC pause after we create the timer
// and select randomly picked this one out of the two available channels.
// We should do one final immediate check below.
}
}
// Return true if we have a slot available immediately and false otherwise.
select {
case <-sem.slots:
return true
default:
return false
}
} | go | func (sem *boundedSemaphore) TryAcquire(timeout time.Duration) bool {
if timeout > 0 {
// Wait until we get a slot or timeout expires.
tm := time.NewTimer(timeout)
defer tm.Stop()
select {
case <-sem.slots:
return true
case <-tm.C:
// Timeout expired. In very rare cases this might happen even if
// there is a slot available, e.g. GC pause after we create the timer
// and select randomly picked this one out of the two available channels.
// We should do one final immediate check below.
}
}
// Return true if we have a slot available immediately and false otherwise.
select {
case <-sem.slots:
return true
default:
return false
}
} | [
"func",
"(",
"sem",
"*",
"boundedSemaphore",
")",
"TryAcquire",
"(",
"timeout",
"time",
".",
"Duration",
")",
"bool",
"{",
"if",
"timeout",
">",
"0",
"{",
"// Wait until we get a slot or timeout expires.",
"tm",
":=",
"time",
".",
"NewTimer",
"(",
"timeout",
")",
"\n",
"defer",
"tm",
".",
"Stop",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"sem",
".",
"slots",
":",
"return",
"true",
"\n",
"case",
"<-",
"tm",
".",
"C",
":",
"// Timeout expired. In very rare cases this might happen even if",
"// there is a slot available, e.g. GC pause after we create the timer",
"// and select randomly picked this one out of the two available channels.",
"// We should do one final immediate check below.",
"}",
"\n",
"}",
"\n\n",
"// Return true if we have a slot available immediately and false otherwise.",
"select",
"{",
"case",
"<-",
"sem",
".",
"slots",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // TryAcquire returns true if it acquires a resource slot within the
// timeout, false otherwise. | [
"TryAcquire",
"returns",
"true",
"if",
"it",
"acquires",
"a",
"resource",
"slot",
"within",
"the",
"timeout",
"false",
"otherwise",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/semaphore.go#L47-L70 | train |
dropbox/godropbox | database/sqlbuilder/expression.go | Literal | func Literal(v interface{}) Expression {
value, err := sqltypes.BuildValue(v)
if err != nil {
panic(errors.Wrap(err, "Invalid literal value"))
}
return &literalExpression{value: value}
} | go | func Literal(v interface{}) Expression {
value, err := sqltypes.BuildValue(v)
if err != nil {
panic(errors.Wrap(err, "Invalid literal value"))
}
return &literalExpression{value: value}
} | [
"func",
"Literal",
"(",
"v",
"interface",
"{",
"}",
")",
"Expression",
"{",
"value",
",",
"err",
":=",
"sqltypes",
".",
"BuildValue",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"literalExpression",
"{",
"value",
":",
"value",
"}",
"\n",
"}"
] | // Returns an escaped literal string | [
"Returns",
"an",
"escaped",
"literal",
"string"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L368-L374 | train |
dropbox/godropbox | database/sqlbuilder/expression.go | Eq | func Eq(lhs, rhs Expression) BoolExpression {
lit, ok := rhs.(*literalExpression)
if ok && sqltypes.Value(lit.value).IsNull() {
return newBoolExpression(lhs, rhs, []byte(" IS "))
}
return newBoolExpression(lhs, rhs, []byte("="))
} | go | func Eq(lhs, rhs Expression) BoolExpression {
lit, ok := rhs.(*literalExpression)
if ok && sqltypes.Value(lit.value).IsNull() {
return newBoolExpression(lhs, rhs, []byte(" IS "))
}
return newBoolExpression(lhs, rhs, []byte("="))
} | [
"func",
"Eq",
"(",
"lhs",
",",
"rhs",
"Expression",
")",
"BoolExpression",
"{",
"lit",
",",
"ok",
":=",
"rhs",
".",
"(",
"*",
"literalExpression",
")",
"\n",
"if",
"ok",
"&&",
"sqltypes",
".",
"Value",
"(",
"lit",
".",
"value",
")",
".",
"IsNull",
"(",
")",
"{",
"return",
"newBoolExpression",
"(",
"lhs",
",",
"rhs",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"newBoolExpression",
"(",
"lhs",
",",
"rhs",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // Returns a representation of "a=b" | [
"Returns",
"a",
"representation",
"of",
"a",
"=",
"b"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L441-L447 | train |
dropbox/godropbox | database/sqlbuilder/expression.go | Lt | func Lt(lhs Expression, rhs Expression) BoolExpression {
return newBoolExpression(lhs, rhs, []byte("<"))
} | go | func Lt(lhs Expression, rhs Expression) BoolExpression {
return newBoolExpression(lhs, rhs, []byte("<"))
} | [
"func",
"Lt",
"(",
"lhs",
"Expression",
",",
"rhs",
"Expression",
")",
"BoolExpression",
"{",
"return",
"newBoolExpression",
"(",
"lhs",
",",
"rhs",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // Returns a representation of "a<b" | [
"Returns",
"a",
"representation",
"of",
"a<b"
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L469-L471 | train |
dropbox/godropbox | memcache/raw_ascii_client.go | NewRawAsciiClient | func NewRawAsciiClient(shard int, channel io.ReadWriter) ClientShard {
return &RawAsciiClient{
shard: shard,
channel: channel,
validState: true,
writer: bufio.NewWriter(channel),
reader: bufio.NewReader(channel),
}
} | go | func NewRawAsciiClient(shard int, channel io.ReadWriter) ClientShard {
return &RawAsciiClient{
shard: shard,
channel: channel,
validState: true,
writer: bufio.NewWriter(channel),
reader: bufio.NewReader(channel),
}
} | [
"func",
"NewRawAsciiClient",
"(",
"shard",
"int",
",",
"channel",
"io",
".",
"ReadWriter",
")",
"ClientShard",
"{",
"return",
"&",
"RawAsciiClient",
"{",
"shard",
":",
"shard",
",",
"channel",
":",
"channel",
",",
"validState",
":",
"true",
",",
"writer",
":",
"bufio",
".",
"NewWriter",
"(",
"channel",
")",
",",
"reader",
":",
"bufio",
".",
"NewReader",
"(",
"channel",
")",
",",
"}",
"\n",
"}"
] | // This creates a new memcache RawAsciiClient. | [
"This",
"creates",
"a",
"new",
"memcache",
"RawAsciiClient",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_ascii_client.go#L30-L38 | train |
dropbox/godropbox | sync2/boundedrwlock.go | NewBoundedRWLock | func NewBoundedRWLock(capacity int) *BoundedRWLock {
return &BoundedRWLock{
waiters: make(chan *rwwait, capacity),
control: &sync.Mutex{},
}
} | go | func NewBoundedRWLock(capacity int) *BoundedRWLock {
return &BoundedRWLock{
waiters: make(chan *rwwait, capacity),
control: &sync.Mutex{},
}
} | [
"func",
"NewBoundedRWLock",
"(",
"capacity",
"int",
")",
"*",
"BoundedRWLock",
"{",
"return",
"&",
"BoundedRWLock",
"{",
"waiters",
":",
"make",
"(",
"chan",
"*",
"rwwait",
",",
"capacity",
")",
",",
"control",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n",
"}"
] | // Create a new BoundedRWLock with the given capacity.
//
// RLocks or WLocks beyond this capacity will fail fast with an error. | [
"Create",
"a",
"new",
"BoundedRWLock",
"with",
"the",
"given",
"capacity",
".",
"RLocks",
"or",
"WLocks",
"beyond",
"this",
"capacity",
"will",
"fail",
"fast",
"with",
"an",
"error",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L32-L37 | train |
dropbox/godropbox | sync2/boundedrwlock.go | RLock | func (rw *BoundedRWLock) RLock(timeout time.Duration) (err error) {
deadline := time.After(timeout)
rw.control.Lock()
if rw.nextWriter != nil {
me := newWait(false)
select {
case rw.waiters <- me:
default:
err = errors.New("Waiter capacity reached in RLock")
}
rw.control.Unlock()
if err != nil {
return
}
woken := me.WaitAtomic(deadline)
if !woken {
return errors.New("Waiter timeout")
}
} else {
rw.readers++
rw.control.Unlock()
}
return
} | go | func (rw *BoundedRWLock) RLock(timeout time.Duration) (err error) {
deadline := time.After(timeout)
rw.control.Lock()
if rw.nextWriter != nil {
me := newWait(false)
select {
case rw.waiters <- me:
default:
err = errors.New("Waiter capacity reached in RLock")
}
rw.control.Unlock()
if err != nil {
return
}
woken := me.WaitAtomic(deadline)
if !woken {
return errors.New("Waiter timeout")
}
} else {
rw.readers++
rw.control.Unlock()
}
return
} | [
"func",
"(",
"rw",
"*",
"BoundedRWLock",
")",
"RLock",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"err",
"error",
")",
"{",
"deadline",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"rw",
".",
"control",
".",
"Lock",
"(",
")",
"\n",
"if",
"rw",
".",
"nextWriter",
"!=",
"nil",
"{",
"me",
":=",
"newWait",
"(",
"false",
")",
"\n",
"select",
"{",
"case",
"rw",
".",
"waiters",
"<-",
"me",
":",
"default",
":",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"rw",
".",
"control",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"woken",
":=",
"me",
".",
"WaitAtomic",
"(",
"deadline",
")",
"\n",
"if",
"!",
"woken",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"rw",
".",
"readers",
"++",
"\n",
"rw",
".",
"control",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Wait for a read lock for up to 'timeout'.
//
// Error will be non-nil on timeout or when the wait list is at capacity. | [
"Wait",
"for",
"a",
"read",
"lock",
"for",
"up",
"to",
"timeout",
".",
"Error",
"will",
"be",
"non",
"-",
"nil",
"on",
"timeout",
"or",
"when",
"the",
"wait",
"list",
"is",
"at",
"capacity",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L42-L66 | train |
dropbox/godropbox | sync2/boundedrwlock.go | WLock | func (rw *BoundedRWLock) WLock(timeout time.Duration) (err error) {
deadline := time.After(timeout)
rw.control.Lock()
if rw.readers != 0 || rw.nextWriter != nil {
me := newWait(true)
if rw.nextWriter == nil {
rw.nextWriter = me
} else {
select {
case rw.waiters <- me:
default:
err = errors.New("Waiter capacity reached in WLock")
}
}
rw.control.Unlock()
if err != nil {
return
}
woken := me.WaitAtomic(deadline)
if !woken {
return errors.New("Waiter timeout")
}
rw.control.Lock()
if rw.readers != 0 {
panic("readers??")
}
if rw.nextWriter != me {
panic("not me??")
}
} else {
rw.nextWriter = newWait(true)
}
rw.control.Unlock()
return
} | go | func (rw *BoundedRWLock) WLock(timeout time.Duration) (err error) {
deadline := time.After(timeout)
rw.control.Lock()
if rw.readers != 0 || rw.nextWriter != nil {
me := newWait(true)
if rw.nextWriter == nil {
rw.nextWriter = me
} else {
select {
case rw.waiters <- me:
default:
err = errors.New("Waiter capacity reached in WLock")
}
}
rw.control.Unlock()
if err != nil {
return
}
woken := me.WaitAtomic(deadline)
if !woken {
return errors.New("Waiter timeout")
}
rw.control.Lock()
if rw.readers != 0 {
panic("readers??")
}
if rw.nextWriter != me {
panic("not me??")
}
} else {
rw.nextWriter = newWait(true)
}
rw.control.Unlock()
return
} | [
"func",
"(",
"rw",
"*",
"BoundedRWLock",
")",
"WLock",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"err",
"error",
")",
"{",
"deadline",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"rw",
".",
"control",
".",
"Lock",
"(",
")",
"\n",
"if",
"rw",
".",
"readers",
"!=",
"0",
"||",
"rw",
".",
"nextWriter",
"!=",
"nil",
"{",
"me",
":=",
"newWait",
"(",
"true",
")",
"\n",
"if",
"rw",
".",
"nextWriter",
"==",
"nil",
"{",
"rw",
".",
"nextWriter",
"=",
"me",
"\n",
"}",
"else",
"{",
"select",
"{",
"case",
"rw",
".",
"waiters",
"<-",
"me",
":",
"default",
":",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"rw",
".",
"control",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"woken",
":=",
"me",
".",
"WaitAtomic",
"(",
"deadline",
")",
"\n",
"if",
"!",
"woken",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"rw",
".",
"control",
".",
"Lock",
"(",
")",
"\n",
"if",
"rw",
".",
"readers",
"!=",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"rw",
".",
"nextWriter",
"!=",
"me",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"rw",
".",
"nextWriter",
"=",
"newWait",
"(",
"true",
")",
"\n",
"}",
"\n",
"rw",
".",
"control",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Lock for writing, waiting up to 'timeout' for successful exclusive
// acquisition of the lock. | [
"Lock",
"for",
"writing",
"waiting",
"up",
"to",
"timeout",
"for",
"successful",
"exclusive",
"acquisition",
"of",
"the",
"lock",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L83-L118 | train |
dropbox/godropbox | sync2/boundedrwlock.go | WaitAtomic | func (wait *rwwait) WaitAtomic(after <-chan time.Time) bool {
select {
case <-wait.wake:
return true
case <-after:
}
swapped := atomic.CompareAndSwapInt32(&wait.alive, 1, 0)
// They're gonna put it.
if !swapped {
<-wait.wake
return true
}
return false
} | go | func (wait *rwwait) WaitAtomic(after <-chan time.Time) bool {
select {
case <-wait.wake:
return true
case <-after:
}
swapped := atomic.CompareAndSwapInt32(&wait.alive, 1, 0)
// They're gonna put it.
if !swapped {
<-wait.wake
return true
}
return false
} | [
"func",
"(",
"wait",
"*",
"rwwait",
")",
"WaitAtomic",
"(",
"after",
"<-",
"chan",
"time",
".",
"Time",
")",
"bool",
"{",
"select",
"{",
"case",
"<-",
"wait",
".",
"wake",
":",
"return",
"true",
"\n",
"case",
"<-",
"after",
":",
"}",
"\n",
"swapped",
":=",
"atomic",
".",
"CompareAndSwapInt32",
"(",
"&",
"wait",
".",
"alive",
",",
"1",
",",
"0",
")",
"\n",
"// They're gonna put it.",
"if",
"!",
"swapped",
"{",
"<-",
"wait",
".",
"wake",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Wait for a signal on the waiter, with the guarantee that both goroutines
// will agree on whether or not the signal was delivered.
//
// Returns true if the wake occurred, false on timeout. | [
"Wait",
"for",
"a",
"signal",
"on",
"the",
"waiter",
"with",
"the",
"guarantee",
"that",
"both",
"goroutines",
"will",
"agree",
"on",
"whether",
"or",
"not",
"the",
"signal",
"was",
"delivered",
".",
"Returns",
"true",
"if",
"the",
"wake",
"occurred",
"false",
"on",
"timeout",
"."
] | 5749d3b71cbefd8eacc316df3f0a6fcb9991bb51 | https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L191-L204 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.