repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
gocql/gocql
policies.go
add
func (c *cowHostList) add(host *HostInfo) bool { c.mu.Lock() l := c.get() if n := len(l); n == 0 { l = []*HostInfo{host} } else { newL := make([]*HostInfo, n+1) for i := 0; i < n; i++ { if host.Equal(l[i]) { c.mu.Unlock() return false } newL[i] = l[i] } newL[n] = host l = newL } c.list.Store(&l) c.mu.Unlock() return true }
go
func (c *cowHostList) add(host *HostInfo) bool { c.mu.Lock() l := c.get() if n := len(l); n == 0 { l = []*HostInfo{host} } else { newL := make([]*HostInfo, n+1) for i := 0; i < n; i++ { if host.Equal(l[i]) { c.mu.Unlock() return false } newL[i] = l[i] } newL[n] = host l = newL } c.list.Store(&l) c.mu.Unlock() return true }
[ "func", "(", "c", "*", "cowHostList", ")", "add", "(", "host", "*", "HostInfo", ")", "bool", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "l", ":=", "c", ".", "get", "(", ")", "\n", "if", "n", ":=", "len", "(", "l", ")", ";", "n", "=...
// add will add a host if it not already in the list
[ "add", "will", "add", "a", "host", "if", "it", "not", "already", "in", "the", "list" ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L47-L69
train
gocql/gocql
policies.go
Attempt
func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool { return q.Attempts() <= s.NumRetries }
go
func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool { return q.Attempts() <= s.NumRetries }
[ "func", "(", "s", "*", "SimpleRetryPolicy", ")", "Attempt", "(", "q", "RetryableQuery", ")", "bool", "{", "return", "q", ".", "Attempts", "(", ")", "<=", "s", ".", "NumRetries", "\n", "}" ]
// Attempt tells gocql to attempt the query again based on query.Attempts being less // than the NumRetries defined in the policy.
[ "Attempt", "tells", "gocql", "to", "attempt", "the", "query", "again", "based", "on", "query", ".", "Attempts", "being", "less", "than", "the", "NumRetries", "defined", "in", "the", "policy", "." ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L179-L181
train
gocql/gocql
policies.go
getExponentialTime
func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration { if min <= 0 { min = 100 * time.Millisecond } if max <= 0 { max = 10 * time.Second } minFloat := float64(min) napDuration := minFloat * math.Pow(2, float64(attempts-1)) // add some jitter napDuration += rand.Float64()*minFloat - (minFloat / 2) if napDuration > float64(max) { return time.Duration(max) } return time.Duration(napDuration) }
go
func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration { if min <= 0 { min = 100 * time.Millisecond } if max <= 0 { max = 10 * time.Second } minFloat := float64(min) napDuration := minFloat * math.Pow(2, float64(attempts-1)) // add some jitter napDuration += rand.Float64()*minFloat - (minFloat / 2) if napDuration > float64(max) { return time.Duration(max) } return time.Duration(napDuration) }
[ "func", "getExponentialTime", "(", "min", "time", ".", "Duration", ",", "max", "time", ".", "Duration", ",", "attempts", "int", ")", "time", ".", "Duration", "{", "if", "min", "<=", "0", "{", "min", "=", "100", "*", "time", ".", "Millisecond", "\n", ...
// used to calculate exponentially growing time
[ "used", "to", "calculate", "exponentially", "growing", "time" ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L202-L217
train
gocql/gocql
policies.go
TokenAwareHostPolicy
func TokenAwareHostPolicy(fallback HostSelectionPolicy, opts ...func(*tokenAwareHostPolicy)) HostSelectionPolicy { p := &tokenAwareHostPolicy{fallback: fallback} for _, opt := range opts { opt(p) } return p }
go
func TokenAwareHostPolicy(fallback HostSelectionPolicy, opts ...func(*tokenAwareHostPolicy)) HostSelectionPolicy { p := &tokenAwareHostPolicy{fallback: fallback} for _, opt := range opts { opt(p) } return p }
[ "func", "TokenAwareHostPolicy", "(", "fallback", "HostSelectionPolicy", ",", "opts", "...", "func", "(", "*", "tokenAwareHostPolicy", ")", ")", "HostSelectionPolicy", "{", "p", ":=", "&", "tokenAwareHostPolicy", "{", "fallback", ":", "fallback", "}", "\n", "for", ...
// TokenAwareHostPolicy is a token aware host selection policy, where hosts are // selected based on the partition key, so queries are sent to the host which // owns the partition. Fallback is used when routing information is not available.
[ "TokenAwareHostPolicy", "is", "a", "token", "aware", "host", "selection", "policy", "where", "hosts", "are", "selected", "based", "on", "the", "partition", "key", "so", "queries", "are", "sent", "to", "the", "host", "which", "owns", "the", "partition", ".", ...
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/policies.go#L393-L399
train
gocql/gocql
address_translators.go
IdentityTranslator
func IdentityTranslator() AddressTranslator { return AddressTranslatorFunc(func(addr net.IP, port int) (net.IP, int) { return addr, port }) }
go
func IdentityTranslator() AddressTranslator { return AddressTranslatorFunc(func(addr net.IP, port int) (net.IP, int) { return addr, port }) }
[ "func", "IdentityTranslator", "(", ")", "AddressTranslator", "{", "return", "AddressTranslatorFunc", "(", "func", "(", "addr", "net", ".", "IP", ",", "port", "int", ")", "(", "net", ".", "IP", ",", "int", ")", "{", "return", "addr", ",", "port", "\n", ...
// IdentityTranslator will do nothing but return what it was provided. It is essentially a no-op.
[ "IdentityTranslator", "will", "do", "nothing", "but", "return", "what", "it", "was", "provided", ".", "It", "is", "essentially", "a", "no", "-", "op", "." ]
b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac
https://github.com/gocql/gocql/blob/b99afaf3b1639e5264f5e1cabf04fdb2e5ed57ac/address_translators.go#L22-L26
train
denisenkom/go-mssqldb
tds.go
normalizeOdbcKey
func normalizeOdbcKey(s string) string { return strings.ToLower(strings.TrimRightFunc(s, unicode.IsSpace)) }
go
func normalizeOdbcKey(s string) string { return strings.ToLower(strings.TrimRightFunc(s, unicode.IsSpace)) }
[ "func", "normalizeOdbcKey", "(", "s", "string", ")", "string", "{", "return", "strings", ".", "ToLower", "(", "strings", ".", "TrimRightFunc", "(", "s", ",", "unicode", ".", "IsSpace", ")", ")", "\n", "}" ]
// Normalizes the given string as an ODBC-format key
[ "Normalizes", "the", "given", "string", "as", "an", "ODBC", "-", "format", "key" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/tds.go#L867-L869
train
denisenkom/go-mssqldb
tds.go
dialConnection
func dialConnection(ctx context.Context, c *Connector, p connectParams) (conn net.Conn, err error) { var ips []net.IP ips, err = net.LookupIP(p.host) if err != nil { ip := net.ParseIP(p.host) if ip == nil { return nil, err } ips = []net.IP{ip} } if len(ips) == 1 { d := c.getDialer(&p) addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port))) conn, err = d.DialContext(ctx, "tcp", addr) } else { //Try Dials in parallel to avoid waiting for timeouts. connChan := make(chan net.Conn, len(ips)) errChan := make(chan error, len(ips)) portStr := strconv.Itoa(int(p.port)) for _, ip := range ips { go func(ip net.IP) { d := c.getDialer(&p) addr := net.JoinHostPort(ip.String(), portStr) conn, err := d.DialContext(ctx, "tcp", addr) if err == nil { connChan <- conn } else { errChan <- err } }(ip) } // Wait for either the *first* successful connection, or all the errors wait_loop: for i, _ := range ips { select { case conn = <-connChan: // Got a connection to use, close any others go func(n int) { for i := 0; i < n; i++ { select { case conn := <-connChan: conn.Close() case <-errChan: } } }(len(ips) - i - 1) // Remove any earlier errors we may have collected err = nil break wait_loop case err = <-errChan: } } } // Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection if conn == nil { f := "Unable to open tcp connection with host '%v:%v': %v" return nil, fmt.Errorf(f, p.host, p.port, err.Error()) } return conn, err }
go
func dialConnection(ctx context.Context, c *Connector, p connectParams) (conn net.Conn, err error) { var ips []net.IP ips, err = net.LookupIP(p.host) if err != nil { ip := net.ParseIP(p.host) if ip == nil { return nil, err } ips = []net.IP{ip} } if len(ips) == 1 { d := c.getDialer(&p) addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port))) conn, err = d.DialContext(ctx, "tcp", addr) } else { //Try Dials in parallel to avoid waiting for timeouts. connChan := make(chan net.Conn, len(ips)) errChan := make(chan error, len(ips)) portStr := strconv.Itoa(int(p.port)) for _, ip := range ips { go func(ip net.IP) { d := c.getDialer(&p) addr := net.JoinHostPort(ip.String(), portStr) conn, err := d.DialContext(ctx, "tcp", addr) if err == nil { connChan <- conn } else { errChan <- err } }(ip) } // Wait for either the *first* successful connection, or all the errors wait_loop: for i, _ := range ips { select { case conn = <-connChan: // Got a connection to use, close any others go func(n int) { for i := 0; i < n; i++ { select { case conn := <-connChan: conn.Close() case <-errChan: } } }(len(ips) - i - 1) // Remove any earlier errors we may have collected err = nil break wait_loop case err = <-errChan: } } } // Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection if conn == nil { f := "Unable to open tcp connection with host '%v:%v': %v" return nil, fmt.Errorf(f, p.host, p.port, err.Error()) } return conn, err }
[ "func", "dialConnection", "(", "ctx", "context", ".", "Context", ",", "c", "*", "Connector", ",", "p", "connectParams", ")", "(", "conn", "net", ".", "Conn", ",", "err", "error", ")", "{", "var", "ips", "[", "]", "net", ".", "IP", "\n", "ips", ",",...
// SQL Server AlwaysOn Availability Group Listeners are bound by DNS to a // list of IP addresses. So if there is more than one, try them all and // use the first one that allows a connection.
[ "SQL", "Server", "AlwaysOn", "Availability", "Group", "Listeners", "are", "bound", "by", "DNS", "to", "a", "list", "of", "IP", "addresses", ".", "So", "if", "there", "is", "more", "than", "one", "try", "them", "all", "and", "use", "the", "first", "one", ...
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/tds.go#L1114-L1174
train
denisenkom/go-mssqldb
mssql_go110.go
Connect
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { conn, err := c.driver.connect(ctx, c, c.params) if err == nil { err = conn.ResetSession(ctx) } return conn, err }
go
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { conn, err := c.driver.connect(ctx, c, c.params) if err == nil { err = conn.ResetSession(ctx) } return conn, err }
[ "func", "(", "c", "*", "Connector", ")", "Connect", "(", "ctx", "context", ".", "Context", ")", "(", "driver", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "c", ".", "driver", ".", "connect", "(", "ctx", ",", "c", ",", "c", "....
// Connect to the server and return a TDS connection.
[ "Connect", "to", "the", "server", "and", "return", "a", "TDS", "connection", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql_go110.go#L36-L42
train
denisenkom/go-mssqldb
batch/batch.go
Split
func Split(sql, separator string) []string { if len(separator) == 0 || len(sql) < len(separator) { return []string{sql} } l := &lexer{ Sql: sql, Sep: separator, At: 0, } state := stateWhitespace for state != nil { state = state(l) } l.AddCurrent(1) return l.Batch }
go
func Split(sql, separator string) []string { if len(separator) == 0 || len(sql) < len(separator) { return []string{sql} } l := &lexer{ Sql: sql, Sep: separator, At: 0, } state := stateWhitespace for state != nil { state = state(l) } l.AddCurrent(1) return l.Batch }
[ "func", "Split", "(", "sql", ",", "separator", "string", ")", "[", "]", "string", "{", "if", "len", "(", "separator", ")", "==", "0", "||", "len", "(", "sql", ")", "<", "len", "(", "separator", ")", "{", "return", "[", "]", "string", "{", "sql", ...
// Split the provided SQL into multiple sql scripts based on a given // separator, often "GO". It also allows escaping newlines with a // backslash.
[ "Split", "the", "provided", "SQL", "into", "multiple", "sql", "scripts", "based", "on", "a", "given", "separator", "often", "GO", ".", "It", "also", "allows", "escaping", "newlines", "with", "a", "backslash", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/batch/batch.go#L20-L35
train
denisenkom/go-mssqldb
bulkcopy.go
AddRow
func (b *Bulk) AddRow(row []interface{}) (err error) { if !b.headerSent { err = b.sendBulkCommand(b.ctx) if err != nil { return } } if len(row) != len(b.bulkColumns) { return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d", len(row), len(b.bulkColumns)) } bytes, err := b.makeRowData(row) if err != nil { return } _, err = b.cn.sess.buf.Write(bytes) if err != nil { return } b.numRows = b.numRows + 1 return }
go
func (b *Bulk) AddRow(row []interface{}) (err error) { if !b.headerSent { err = b.sendBulkCommand(b.ctx) if err != nil { return } } if len(row) != len(b.bulkColumns) { return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d", len(row), len(b.bulkColumns)) } bytes, err := b.makeRowData(row) if err != nil { return } _, err = b.cn.sess.buf.Write(bytes) if err != nil { return } b.numRows = b.numRows + 1 return }
[ "func", "(", "b", "*", "Bulk", ")", "AddRow", "(", "row", "[", "]", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "if", "!", "b", ".", "headerSent", "{", "err", "=", "b", ".", "sendBulkCommand", "(", "b", ".", "ctx", ")", "\n", "...
// AddRow immediately writes the row to the destination table. // The arguments are the row values in the order they were specified.
[ "AddRow", "immediately", "writes", "the", "row", "to", "the", "destination", "table", ".", "The", "arguments", "are", "the", "row", "values", "in", "the", "order", "they", "were", "specified", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/bulkcopy.go#L154-L179
train
denisenkom/go-mssqldb
mssql.go
OpenConnector
func (d *Driver) OpenConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } return &Connector{ params: params, driver: d, }, nil }
go
func (d *Driver) OpenConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } return &Connector{ params: params, driver: d, }, nil }
[ "func", "(", "d", "*", "Driver", ")", "OpenConnector", "(", "dsn", "string", ")", "(", "*", "Connector", ",", "error", ")", "{", "params", ",", "err", ":=", "parseConnectParams", "(", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ...
// OpenConnector opens a new connector. Useful to dial with a context.
[ "OpenConnector", "opens", "a", "new", "connector", ".", "Useful", "to", "dial", "with", "a", "context", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L54-L63
train
denisenkom/go-mssqldb
mssql.go
NewConnector
func NewConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } c := &Connector{ params: params, driver: driverInstanceNoProcess, } return c, nil }
go
func NewConnector(dsn string) (*Connector, error) { params, err := parseConnectParams(dsn) if err != nil { return nil, err } c := &Connector{ params: params, driver: driverInstanceNoProcess, } return c, nil }
[ "func", "NewConnector", "(", "dsn", "string", ")", "(", "*", "Connector", ",", "error", ")", "{", "params", ",", "err", ":=", "parseConnectParams", "(", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", ...
// NewConnector creates a new connector from a DSN. // The returned connector may be used with sql.OpenDB.
[ "NewConnector", "creates", "a", "new", "connector", "from", "a", "DSN", ".", "The", "returned", "connector", "may", "be", "used", "with", "sql", ".", "OpenDB", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L80-L90
train
denisenkom/go-mssqldb
mssql.go
connect
func (d *Driver) connect(ctx context.Context, c *Connector, params connectParams) (*Conn, error) { sess, err := connect(ctx, c, d.log, params) if err != nil { // main server failed, try fail-over partner if params.failOverPartner == "" { return nil, err } params.host = params.failOverPartner if params.failOverPort != 0 { params.port = params.failOverPort } sess, err = connect(ctx, c, d.log, params) if err != nil { // fail-over partner also failed, now fail return nil, err } } conn := &Conn{ connector: c, sess: sess, transactionCtx: context.Background(), processQueryText: d.processQueryText, connectionGood: true, } conn.sess.log = d.log return conn, nil }
go
func (d *Driver) connect(ctx context.Context, c *Connector, params connectParams) (*Conn, error) { sess, err := connect(ctx, c, d.log, params) if err != nil { // main server failed, try fail-over partner if params.failOverPartner == "" { return nil, err } params.host = params.failOverPartner if params.failOverPort != 0 { params.port = params.failOverPort } sess, err = connect(ctx, c, d.log, params) if err != nil { // fail-over partner also failed, now fail return nil, err } } conn := &Conn{ connector: c, sess: sess, transactionCtx: context.Background(), processQueryText: d.processQueryText, connectionGood: true, } conn.sess.log = d.log return conn, nil }
[ "func", "(", "d", "*", "Driver", ")", "connect", "(", "ctx", "context", ".", "Context", ",", "c", "*", "Connector", ",", "params", "connectParams", ")", "(", "*", "Conn", ",", "error", ")", "{", "sess", ",", "err", ":=", "connect", "(", "ctx", ",",...
// connect to the server, using the provided context for dialing only.
[ "connect", "to", "the", "server", "using", "the", "provided", "context", "for", "dialing", "only", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L327-L357
train
denisenkom/go-mssqldb
mssql.go
isProc
func isProc(s string) bool { if len(s) == 0 { return false } const ( outside = iota text escaped ) st := outside var rn1, rPrev rune for _, r := range s { rPrev = rn1 rn1 = r switch r { // No newlines or string sequences. case '\n', '\r', '\'', ';': return false } switch st { case outside: switch { case unicode.IsSpace(r): return false case r == '[': st = escaped continue case r == ']' && rPrev == ']': st = escaped continue case unicode.IsLetter(r): st = text } case text: switch { case r == '.': st = outside continue case unicode.IsSpace(r): return false } case escaped: switch { case r == ']': st = outside continue } } } return true }
go
func isProc(s string) bool { if len(s) == 0 { return false } const ( outside = iota text escaped ) st := outside var rn1, rPrev rune for _, r := range s { rPrev = rn1 rn1 = r switch r { // No newlines or string sequences. case '\n', '\r', '\'', ';': return false } switch st { case outside: switch { case unicode.IsSpace(r): return false case r == '[': st = escaped continue case r == ']' && rPrev == ']': st = escaped continue case unicode.IsLetter(r): st = text } case text: switch { case r == '.': st = outside continue case unicode.IsSpace(r): return false } case escaped: switch { case r == ']': st = outside continue } } } return true }
[ "func", "isProc", "(", "s", "string", ")", "bool", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "const", "(", "outside", "=", "iota", "\n", "text", "\n", "escaped", "\n", ")", "\n", "st", ":=", "outside", ...
// isProc takes the query text in s and determines if it is a stored proc name // or SQL text.
[ "isProc", "takes", "the", "query", "text", "in", "s", "and", "determines", "if", "it", "is", "a", "stored", "proc", "name", "or", "SQL", "text", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L485-L535
train
denisenkom/go-mssqldb
mssql.go
ColumnTypeNullable
func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool) { nullable = r.cols[index].Flags&colFlagNullable != 0 ok = true return }
go
func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool) { nullable = r.cols[index].Flags&colFlagNullable != 0 ok = true return }
[ "func", "(", "r", "*", "Rows", ")", "ColumnTypeNullable", "(", "index", "int", ")", "(", "nullable", ",", "ok", "bool", ")", "{", "nullable", "=", "r", ".", "cols", "[", "index", "]", ".", "Flags", "&", "colFlagNullable", "!=", "0", "\n", "ok", "="...
// The nullable value should // be true if it is known the column may be null, or false if the column is known // to be not nullable. // If the column nullability is unknown, ok should be false.
[ "The", "nullable", "value", "should", "be", "true", "if", "it", "is", "known", "the", "column", "may", "be", "null", "or", "false", "if", "the", "column", "is", "known", "to", "be", "not", "nullable", ".", "If", "the", "column", "nullability", "is", "u...
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L779-L783
train
denisenkom/go-mssqldb
mssql.go
Ping
func (c *Conn) Ping(ctx context.Context) error { if !c.connectionGood { return driver.ErrBadConn } stmt := &Stmt{c, `select 1;`, 0, nil} _, err := stmt.ExecContext(ctx, nil) return err }
go
func (c *Conn) Ping(ctx context.Context) error { if !c.connectionGood { return driver.ErrBadConn } stmt := &Stmt{c, `select 1;`, 0, nil} _, err := stmt.ExecContext(ctx, nil) return err }
[ "func", "(", "c", "*", "Conn", ")", "Ping", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "!", "c", ".", "connectionGood", "{", "return", "driver", ".", "ErrBadConn", "\n", "}", "\n", "stmt", ":=", "&", "Stmt", "{", "c", ",", "`...
// Ping is used to check if the remote server is available and satisfies the Pinger interface.
[ "Ping", "is", "used", "to", "check", "if", "the", "remote", "server", "is", "available", "and", "satisfies", "the", "Pinger", "interface", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L898-L905
train
denisenkom/go-mssqldb
mssql.go
BeginTx
func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if !c.connectionGood { return nil, driver.ErrBadConn } if opts.ReadOnly { return nil, errors.New("Read-only transactions are not supported") } var tdsIsolation isoLevel switch sql.IsolationLevel(opts.Isolation) { case sql.LevelDefault: tdsIsolation = isolationUseCurrent case sql.LevelReadUncommitted: tdsIsolation = isolationReadUncommited case sql.LevelReadCommitted: tdsIsolation = isolationReadCommited case sql.LevelWriteCommitted: return nil, errors.New("LevelWriteCommitted isolation level is not supported") case sql.LevelRepeatableRead: tdsIsolation = isolationRepeatableRead case sql.LevelSnapshot: tdsIsolation = isolationSnapshot case sql.LevelSerializable: tdsIsolation = isolationSerializable case sql.LevelLinearizable: return nil, errors.New("LevelLinearizable isolation level is not supported") default: return nil, errors.New("Isolation level is not supported or unknown") } return c.begin(ctx, tdsIsolation) }
go
func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if !c.connectionGood { return nil, driver.ErrBadConn } if opts.ReadOnly { return nil, errors.New("Read-only transactions are not supported") } var tdsIsolation isoLevel switch sql.IsolationLevel(opts.Isolation) { case sql.LevelDefault: tdsIsolation = isolationUseCurrent case sql.LevelReadUncommitted: tdsIsolation = isolationReadUncommited case sql.LevelReadCommitted: tdsIsolation = isolationReadCommited case sql.LevelWriteCommitted: return nil, errors.New("LevelWriteCommitted isolation level is not supported") case sql.LevelRepeatableRead: tdsIsolation = isolationRepeatableRead case sql.LevelSnapshot: tdsIsolation = isolationSnapshot case sql.LevelSerializable: tdsIsolation = isolationSerializable case sql.LevelLinearizable: return nil, errors.New("LevelLinearizable isolation level is not supported") default: return nil, errors.New("Isolation level is not supported or unknown") } return c.begin(ctx, tdsIsolation) }
[ "func", "(", "c", "*", "Conn", ")", "BeginTx", "(", "ctx", "context", ".", "Context", ",", "opts", "driver", ".", "TxOptions", ")", "(", "driver", ".", "Tx", ",", "error", ")", "{", "if", "!", "c", ".", "connectionGood", "{", "return", "nil", ",", ...
// BeginTx satisfies ConnBeginTx.
[ "BeginTx", "satisfies", "ConnBeginTx", "." ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/mssql.go#L910-L940
train
denisenkom/go-mssqldb
types.go
encodeDateTime
func encodeDateTime(t time.Time) (res []byte) { // base date in days since Jan 1st 1900 basedays := gregorianDays(1900, 1) // days since Jan 1st 1900 (same TZ as t) days := gregorianDays(t.Year(), t.YearDay()) - basedays tm := 300*(t.Second()+t.Minute()*60+t.Hour()*60*60) + t.Nanosecond()*300/1e9 // minimum and maximum possible mindays := gregorianDays(1753, 1) - basedays maxdays := gregorianDays(9999, 365) - basedays if days < mindays { days = mindays tm = 0 } if days > maxdays { days = maxdays tm = (23*60*60+59*60+59)*300 + 299 } res = make([]byte, 8) binary.LittleEndian.PutUint32(res[0:4], uint32(days)) binary.LittleEndian.PutUint32(res[4:8], uint32(tm)) return }
go
func encodeDateTime(t time.Time) (res []byte) { // base date in days since Jan 1st 1900 basedays := gregorianDays(1900, 1) // days since Jan 1st 1900 (same TZ as t) days := gregorianDays(t.Year(), t.YearDay()) - basedays tm := 300*(t.Second()+t.Minute()*60+t.Hour()*60*60) + t.Nanosecond()*300/1e9 // minimum and maximum possible mindays := gregorianDays(1753, 1) - basedays maxdays := gregorianDays(9999, 365) - basedays if days < mindays { days = mindays tm = 0 } if days > maxdays { days = maxdays tm = (23*60*60+59*60+59)*300 + 299 } res = make([]byte, 8) binary.LittleEndian.PutUint32(res[0:4], uint32(days)) binary.LittleEndian.PutUint32(res[4:8], uint32(tm)) return }
[ "func", "encodeDateTime", "(", "t", "time", ".", "Time", ")", "(", "res", "[", "]", "byte", ")", "{", "basedays", ":=", "gregorianDays", "(", "1900", ",", "1", ")", "\n", "days", ":=", "gregorianDays", "(", "t", ".", "Year", "(", ")", ",", "t", "...
// encodes datetime value // type identifier is typeDateTimeN
[ "encodes", "datetime", "value", "type", "identifier", "is", "typeDateTimeN" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/types.go#L279-L300
train
denisenkom/go-mssqldb
types.go
encodeTimeInt
func encodeTimeInt(seconds, ns, scale int, buf []byte) { ns_total := int64(seconds)*1000*1000*1000 + int64(ns) t := ns_total / int64(math.Pow10(int(scale)*-1)*1e9) buf[0] = byte(t) buf[1] = byte(t >> 8) buf[2] = byte(t >> 16) buf[3] = byte(t >> 24) buf[4] = byte(t >> 32) }
go
func encodeTimeInt(seconds, ns, scale int, buf []byte) { ns_total := int64(seconds)*1000*1000*1000 + int64(ns) t := ns_total / int64(math.Pow10(int(scale)*-1)*1e9) buf[0] = byte(t) buf[1] = byte(t >> 8) buf[2] = byte(t >> 16) buf[3] = byte(t >> 24) buf[4] = byte(t >> 32) }
[ "func", "encodeTimeInt", "(", "seconds", ",", "ns", ",", "scale", "int", ",", "buf", "[", "]", "byte", ")", "{", "ns_total", ":=", "int64", "(", "seconds", ")", "*", "1000", "*", "1000", "*", "1000", "+", "int64", "(", "ns", ")", "\n", "t", ":=",...
// writes time value into a field buffer // buffer should be at least calcTimeSize long
[ "writes", "time", "value", "into", "a", "field", "buffer", "buffer", "should", "be", "at", "least", "calcTimeSize", "long" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/types.go#L899-L907
train
denisenkom/go-mssqldb
types.go
gregorianDays
func gregorianDays(year, yearday int) int { year0 := year - 1 return year0*365 + year0/4 - year0/100 + year0/400 + yearday - 1 }
go
func gregorianDays(year, yearday int) int { year0 := year - 1 return year0*365 + year0/4 - year0/100 + year0/400 + yearday - 1 }
[ "func", "gregorianDays", "(", "year", ",", "yearday", "int", ")", "int", "{", "year0", ":=", "year", "-", "1", "\n", "return", "year0", "*", "365", "+", "year0", "/", "4", "-", "year0", "/", "100", "+", "year0", "/", "400", "+", "yearday", "-", "...
// returns days since Jan 1st 0001 in Gregorian calendar
[ "returns", "days", "since", "Jan", "1st", "0001", "in", "Gregorian", "calendar" ]
731ef375ac027e24d275c5432221dbec5007a647
https://github.com/denisenkom/go-mssqldb/blob/731ef375ac027e24d275c5432221dbec5007a647/types.go#L966-L969
train
nsqio/go-nsq
config.go
HandlesOption
func (h *structTagsConfig) HandlesOption(c *Config, option string) bool { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if opt == option { return true } } return false }
go
func (h *structTagsConfig) HandlesOption(c *Config, option string) bool { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if opt == option { return true } } return false }
[ "func", "(", "h", "*", "structTagsConfig", ")", "HandlesOption", "(", "c", "*", "Config", ",", "option", "string", ")", "bool", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "c", ")", ".", "Elem", "(", ")", "\n", "typ", ":=", "val", ".", "Type"...
// Handle options that are listed in StructTags
[ "Handle", "options", "that", "are", "listed", "in", "StructTags" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/config.go#L259-L270
train
nsqio/go-nsq
config.go
Set
func (h *structTagsConfig) Set(c *Config, option string, value interface{}) error { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if option != opt { continue } min := field.Tag.Get("min") max := field.Tag.Get("max") fieldVal := val.FieldByName(field.Name) dest := unsafeValueOf(fieldVal) coercedVal, err := coerce(value, field.Type) if err != nil { return fmt.Errorf("failed to coerce option %s (%v) - %s", option, value, err) } if min != "" { coercedMinVal, _ := coerce(min, field.Type) if valueCompare(coercedVal, coercedMinVal) == -1 { return fmt.Errorf("invalid %s ! %v < %v", option, coercedVal.Interface(), coercedMinVal.Interface()) } } if max != "" { coercedMaxVal, _ := coerce(max, field.Type) if valueCompare(coercedVal, coercedMaxVal) == 1 { return fmt.Errorf("invalid %s ! %v > %v", option, coercedVal.Interface(), coercedMaxVal.Interface()) } } if coercedVal.Type().String() == "nsq.BackoffStrategy" { v := coercedVal.Interface().(BackoffStrategy) if v, ok := v.(interface { setConfig(*Config) }); ok { v.setConfig(c) } } dest.Set(coercedVal) return nil } return fmt.Errorf("unknown option %s", option) }
go
func (h *structTagsConfig) Set(c *Config, option string, value interface{}) error { val := reflect.ValueOf(c).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) opt := field.Tag.Get("opt") if option != opt { continue } min := field.Tag.Get("min") max := field.Tag.Get("max") fieldVal := val.FieldByName(field.Name) dest := unsafeValueOf(fieldVal) coercedVal, err := coerce(value, field.Type) if err != nil { return fmt.Errorf("failed to coerce option %s (%v) - %s", option, value, err) } if min != "" { coercedMinVal, _ := coerce(min, field.Type) if valueCompare(coercedVal, coercedMinVal) == -1 { return fmt.Errorf("invalid %s ! %v < %v", option, coercedVal.Interface(), coercedMinVal.Interface()) } } if max != "" { coercedMaxVal, _ := coerce(max, field.Type) if valueCompare(coercedVal, coercedMaxVal) == 1 { return fmt.Errorf("invalid %s ! %v > %v", option, coercedVal.Interface(), coercedMaxVal.Interface()) } } if coercedVal.Type().String() == "nsq.BackoffStrategy" { v := coercedVal.Interface().(BackoffStrategy) if v, ok := v.(interface { setConfig(*Config) }); ok { v.setConfig(c) } } dest.Set(coercedVal) return nil } return fmt.Errorf("unknown option %s", option) }
[ "func", "(", "h", "*", "structTagsConfig", ")", "Set", "(", "c", "*", "Config", ",", "option", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "c", ")", ".", "Elem", "(", ")", "\n", "...
// Set values based on parameters in StructTags
[ "Set", "values", "based", "on", "parameters", "in", "StructTags" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/config.go#L273-L320
train
nsqio/go-nsq
config.go
unsafeValueOf
func unsafeValueOf(val reflect.Value) reflect.Value { uptr := unsafe.Pointer(val.UnsafeAddr()) return reflect.NewAt(val.Type(), uptr).Elem() }
go
func unsafeValueOf(val reflect.Value) reflect.Value { uptr := unsafe.Pointer(val.UnsafeAddr()) return reflect.NewAt(val.Type(), uptr).Elem() }
[ "func", "unsafeValueOf", "(", "val", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "uptr", ":=", "unsafe", ".", "Pointer", "(", "val", ".", "UnsafeAddr", "(", ")", ")", "\n", "return", "reflect", ".", "NewAt", "(", "val", ".", "Type", "...
// because Config contains private structs we can't use reflect.Value // directly, instead we need to "unsafely" address the variable
[ "because", "Config", "contains", "private", "structs", "we", "can", "t", "use", "reflect", ".", "Value", "directly", "instead", "we", "need", "to", "unsafely", "address", "the", "variable" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/config.go#L479-L482
train
nsqio/go-nsq
protocol.go
ReadUnpackedResponse
func ReadUnpackedResponse(r io.Reader) (int32, []byte, error) { resp, err := ReadResponse(r) if err != nil { return -1, nil, err } return UnpackResponse(resp) }
go
func ReadUnpackedResponse(r io.Reader) (int32, []byte, error) { resp, err := ReadResponse(r) if err != nil { return -1, nil, err } return UnpackResponse(resp) }
[ "func", "ReadUnpackedResponse", "(", "r", "io", ".", "Reader", ")", "(", "int32", ",", "[", "]", "byte", ",", "error", ")", "{", "resp", ",", "err", ":=", "ReadResponse", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ","...
// ReadUnpackedResponse reads and parses data from the underlying // TCP connection according to the NSQ TCP protocol spec and // returns the frameType, data or error
[ "ReadUnpackedResponse", "reads", "and", "parses", "data", "from", "the", "underlying", "TCP", "connection", "according", "to", "the", "NSQ", "TCP", "protocol", "spec", "and", "returns", "the", "frameType", "data", "or", "error" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/protocol.go#L90-L96
train
nsqio/go-nsq
conn.go
NewConn
func NewConn(addr string, config *Config, delegate ConnDelegate) *Conn { if !config.initialized { panic("Config must be created with NewConfig()") } return &Conn{ addr: addr, config: config, delegate: delegate, maxRdyCount: 2500, lastMsgTimestamp: time.Now().UnixNano(), cmdChan: make(chan *Command), msgResponseChan: make(chan *msgResponse), exitChan: make(chan int), drainReady: make(chan int), } }
go
func NewConn(addr string, config *Config, delegate ConnDelegate) *Conn { if !config.initialized { panic("Config must be created with NewConfig()") } return &Conn{ addr: addr, config: config, delegate: delegate, maxRdyCount: 2500, lastMsgTimestamp: time.Now().UnixNano(), cmdChan: make(chan *Command), msgResponseChan: make(chan *msgResponse), exitChan: make(chan int), drainReady: make(chan int), } }
[ "func", "NewConn", "(", "addr", "string", ",", "config", "*", "Config", ",", "delegate", "ConnDelegate", ")", "*", "Conn", "{", "if", "!", "config", ".", "initialized", "{", "panic", "(", "\"Config must be created with NewConfig()\"", ")", "\n", "}", "\n", "...
// NewConn returns a new Conn instance
[ "NewConn", "returns", "a", "new", "Conn", "instance" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L89-L107
train
nsqio/go-nsq
conn.go
Close
func (c *Conn) Close() error { atomic.StoreInt32(&c.closeFlag, 1) if c.conn != nil && atomic.LoadInt64(&c.messagesInFlight) == 0 { return c.conn.CloseRead() } return nil }
go
func (c *Conn) Close() error { atomic.StoreInt32(&c.closeFlag, 1) if c.conn != nil && atomic.LoadInt64(&c.messagesInFlight) == 0 { return c.conn.CloseRead() } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Close", "(", ")", "error", "{", "atomic", ".", "StoreInt32", "(", "&", "c", ".", "closeFlag", ",", "1", ")", "\n", "if", "c", ".", "conn", "!=", "nil", "&&", "atomic", ".", "LoadInt64", "(", "&", "c", ".", ...
// Close idempotently initiates connection close
[ "Close", "idempotently", "initiates", "connection", "close" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L187-L193
train
nsqio/go-nsq
conn.go
SetRDY
func (c *Conn) SetRDY(rdy int64) { atomic.StoreInt64(&c.rdyCount, rdy) if rdy > 0 { atomic.StoreInt64(&c.lastRdyTimestamp, time.Now().UnixNano()) } }
go
func (c *Conn) SetRDY(rdy int64) { atomic.StoreInt64(&c.rdyCount, rdy) if rdy > 0 { atomic.StoreInt64(&c.lastRdyTimestamp, time.Now().UnixNano()) } }
[ "func", "(", "c", "*", "Conn", ")", "SetRDY", "(", "rdy", "int64", ")", "{", "atomic", ".", "StoreInt64", "(", "&", "c", ".", "rdyCount", ",", "rdy", ")", "\n", "if", "rdy", ">", "0", "{", "atomic", ".", "StoreInt64", "(", "&", "c", ".", "lastR...
// SetRDY stores the specified RDY count
[ "SetRDY", "stores", "the", "specified", "RDY", "count" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L213-L218
train
nsqio/go-nsq
conn.go
LastRdyTime
func (c *Conn) LastRdyTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastRdyTimestamp)) }
go
func (c *Conn) LastRdyTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastRdyTimestamp)) }
[ "func", "(", "c", "*", "Conn", ")", "LastRdyTime", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "atomic", ".", "LoadInt64", "(", "&", "c", ".", "lastRdyTimestamp", ")", ")", "\n", "}" ]
// LastRdyTime returns the time of the last non-zero RDY // update for this connection
[ "LastRdyTime", "returns", "the", "time", "of", "the", "last", "non", "-", "zero", "RDY", "update", "for", "this", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L228-L230
train
nsqio/go-nsq
conn.go
LastMessageTime
func (c *Conn) LastMessageTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastMsgTimestamp)) }
go
func (c *Conn) LastMessageTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastMsgTimestamp)) }
[ "func", "(", "c", "*", "Conn", ")", "LastMessageTime", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "atomic", ".", "LoadInt64", "(", "&", "c", ".", "lastMsgTimestamp", ")", ")", "\n", "}" ]
// LastMessageTime returns a time.Time representing // the time at which the last message was received
[ "LastMessageTime", "returns", "a", "time", ".", "Time", "representing", "the", "time", "at", "which", "the", "last", "message", "was", "received" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L234-L236
train
nsqio/go-nsq
conn.go
Read
func (c *Conn) Read(p []byte) (int, error) { c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout)) return c.r.Read(p) }
go
func (c *Conn) Read(p []byte) (int, error) { c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout)) return c.r.Read(p) }
[ "func", "(", "c", "*", "Conn", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "c", ".", "conn", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "c", ".", "config", ".", "ReadTimeo...
// Read performs a deadlined read on the underlying TCP connection
[ "Read", "performs", "a", "deadlined", "read", "on", "the", "underlying", "TCP", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L249-L252
train
nsqio/go-nsq
conn.go
Write
func (c *Conn) Write(p []byte) (int, error) { c.conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout)) return c.w.Write(p) }
go
func (c *Conn) Write(p []byte) (int, error) { c.conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout)) return c.w.Write(p) }
[ "func", "(", "c", "*", "Conn", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "c", ".", "conn", ".", "SetWriteDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "c", ".", "config", ".", "WriteTi...
// Write performs a deadlined write on the underlying TCP connection
[ "Write", "performs", "a", "deadlined", "write", "on", "the", "underlying", "TCP", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L255-L258
train
nsqio/go-nsq
conn.go
WriteCommand
func (c *Conn) WriteCommand(cmd *Command) error { c.mtx.Lock() _, err := cmd.WriteTo(c) if err != nil { goto exit } err = c.Flush() exit: c.mtx.Unlock() if err != nil { c.log(LogLevelError, "IO error - %s", err) c.delegate.OnIOError(c, err) } return err }
go
func (c *Conn) WriteCommand(cmd *Command) error { c.mtx.Lock() _, err := cmd.WriteTo(c) if err != nil { goto exit } err = c.Flush() exit: c.mtx.Unlock() if err != nil { c.log(LogLevelError, "IO error - %s", err) c.delegate.OnIOError(c, err) } return err }
[ "func", "(", "c", "*", "Conn", ")", "WriteCommand", "(", "cmd", "*", "Command", ")", "error", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "_", ",", "err", ":=", "cmd", ".", "WriteTo", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{",...
// WriteCommand is a goroutine safe method to write a Command // to this connection, and flush.
[ "WriteCommand", "is", "a", "goroutine", "safe", "method", "to", "write", "a", "Command", "to", "this", "connection", "and", "flush", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L262-L278
train
nsqio/go-nsq
conn.go
Flush
func (c *Conn) Flush() error { if f, ok := c.w.(flusher); ok { return f.Flush() } return nil }
go
func (c *Conn) Flush() error { if f, ok := c.w.(flusher); ok { return f.Flush() } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Flush", "(", ")", "error", "{", "if", "f", ",", "ok", ":=", "c", ".", "w", ".", "(", "flusher", ")", ";", "ok", "{", "return", "f", ".", "Flush", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Flush writes all buffered data to the underlying TCP connection
[ "Flush", "writes", "all", "buffered", "data", "to", "the", "underlying", "TCP", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L285-L290
train
nsqio/go-nsq
command.go
String
func (c *Command) String() string { if len(c.Params) > 0 { return fmt.Sprintf("%s %s", c.Name, string(bytes.Join(c.Params, byteSpace))) } return string(c.Name) }
go
func (c *Command) String() string { if len(c.Params) > 0 { return fmt.Sprintf("%s %s", c.Name, string(bytes.Join(c.Params, byteSpace))) } return string(c.Name) }
[ "func", "(", "c", "*", "Command", ")", "String", "(", ")", "string", "{", "if", "len", "(", "c", ".", "Params", ")", ">", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s %s\"", ",", "c", ".", "Name", ",", "string", "(", "bytes", ".", "Joi...
// String returns the name and parameters of the Command
[ "String", "returns", "the", "name", "and", "parameters", "of", "the", "Command" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L24-L29
train
nsqio/go-nsq
command.go
WriteTo
func (c *Command) WriteTo(w io.Writer) (int64, error) { var total int64 var buf [4]byte n, err := w.Write(c.Name) total += int64(n) if err != nil { return total, err } for _, param := range c.Params { n, err := w.Write(byteSpace) total += int64(n) if err != nil { return total, err } n, err = w.Write(param) total += int64(n) if err != nil { return total, err } } n, err = w.Write(byteNewLine) total += int64(n) if err != nil { return total, err } if c.Body != nil { bufs := buf[:] binary.BigEndian.PutUint32(bufs, uint32(len(c.Body))) n, err := w.Write(bufs) total += int64(n) if err != nil { return total, err } n, err = w.Write(c.Body) total += int64(n) if err != nil { return total, err } } return total, nil }
go
func (c *Command) WriteTo(w io.Writer) (int64, error) { var total int64 var buf [4]byte n, err := w.Write(c.Name) total += int64(n) if err != nil { return total, err } for _, param := range c.Params { n, err := w.Write(byteSpace) total += int64(n) if err != nil { return total, err } n, err = w.Write(param) total += int64(n) if err != nil { return total, err } } n, err = w.Write(byteNewLine) total += int64(n) if err != nil { return total, err } if c.Body != nil { bufs := buf[:] binary.BigEndian.PutUint32(bufs, uint32(len(c.Body))) n, err := w.Write(bufs) total += int64(n) if err != nil { return total, err } n, err = w.Write(c.Body) total += int64(n) if err != nil { return total, err } } return total, nil }
[ "func", "(", "c", "*", "Command", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "var", "total", "int64", "\n", "var", "buf", "[", "4", "]", "byte", "\n", "n", ",", "err", ":=", "w", ".", "Write", "(...
// WriteTo implements the WriterTo interface and // serializes the Command to the supplied Writer. // // It is suggested that the target Writer is buffered // to avoid performing many system calls.
[ "WriteTo", "implements", "the", "WriterTo", "interface", "and", "serializes", "the", "Command", "to", "the", "supplied", "Writer", ".", "It", "is", "suggested", "that", "the", "target", "Writer", "is", "buffered", "to", "avoid", "performing", "many", "system", ...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L36-L81
train
nsqio/go-nsq
command.go
Auth
func Auth(secret string) (*Command, error) { return &Command{[]byte("AUTH"), nil, []byte(secret)}, nil }
go
func Auth(secret string) (*Command, error) { return &Command{[]byte("AUTH"), nil, []byte(secret)}, nil }
[ "func", "Auth", "(", "secret", "string", ")", "(", "*", "Command", ",", "error", ")", "{", "return", "&", "Command", "{", "[", "]", "byte", "(", "\"AUTH\"", ")", ",", "nil", ",", "[", "]", "byte", "(", "secret", ")", "}", ",", "nil", "\n", "}" ...
// Auth sends credentials for authentication // // After `Identify`, this is usually the first message sent, if auth is used.
[ "Auth", "sends", "credentials", "for", "authentication", "After", "Identify", "this", "is", "usually", "the", "first", "message", "sent", "if", "auth", "is", "used", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L102-L104
train
nsqio/go-nsq
command.go
Publish
func Publish(topic string, body []byte) *Command { var params = [][]byte{[]byte(topic)} return &Command{[]byte("PUB"), params, body} }
go
func Publish(topic string, body []byte) *Command { var params = [][]byte{[]byte(topic)} return &Command{[]byte("PUB"), params, body} }
[ "func", "Publish", "(", "topic", "string", ",", "body", "[", "]", "byte", ")", "*", "Command", "{", "var", "params", "=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "topic", ")", "}", "\n", "return", "&", "Command", "{", "[", "]", ...
// Publish creates a new Command to write a message to a given topic
[ "Publish", "creates", "a", "new", "Command", "to", "write", "a", "message", "to", "a", "given", "topic" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L131-L134
train
nsqio/go-nsq
command.go
DeferredPublish
func DeferredPublish(topic string, delay time.Duration, body []byte) *Command { var params = [][]byte{[]byte(topic), []byte(strconv.Itoa(int(delay / time.Millisecond)))} return &Command{[]byte("DPUB"), params, body} }
go
func DeferredPublish(topic string, delay time.Duration, body []byte) *Command { var params = [][]byte{[]byte(topic), []byte(strconv.Itoa(int(delay / time.Millisecond)))} return &Command{[]byte("DPUB"), params, body} }
[ "func", "DeferredPublish", "(", "topic", "string", ",", "delay", "time", ".", "Duration", ",", "body", "[", "]", "byte", ")", "*", "Command", "{", "var", "params", "=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "topic", ")", ",", "[...
// DeferredPublish creates a new Command to write a message to a given topic // where the message will queue at the channel level until the timeout expires
[ "DeferredPublish", "creates", "a", "new", "Command", "to", "write", "a", "message", "to", "a", "given", "topic", "where", "the", "message", "will", "queue", "at", "the", "channel", "level", "until", "the", "timeout", "expires" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L138-L141
train
nsqio/go-nsq
command.go
Ready
func Ready(count int) *Command { var params = [][]byte{[]byte(strconv.Itoa(count))} return &Command{[]byte("RDY"), params, nil} }
go
func Ready(count int) *Command { var params = [][]byte{[]byte(strconv.Itoa(count))} return &Command{[]byte("RDY"), params, nil} }
[ "func", "Ready", "(", "count", "int", ")", "*", "Command", "{", "var", "params", "=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "count", ")", ")", "}", "\n", "return", "&", "Command", "{", "[", "]", ...
// Ready creates a new Command to specify // the number of messages a client is willing to receive
[ "Ready", "creates", "a", "new", "Command", "to", "specify", "the", "number", "of", "messages", "a", "client", "is", "willing", "to", "receive" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L182-L185
train
nsqio/go-nsq
consumer.go
Stats
func (r *Consumer) Stats() *ConsumerStats { return &ConsumerStats{ MessagesReceived: atomic.LoadUint64(&r.messagesReceived), MessagesFinished: atomic.LoadUint64(&r.messagesFinished), MessagesRequeued: atomic.LoadUint64(&r.messagesRequeued), Connections: len(r.conns()), } }
go
func (r *Consumer) Stats() *ConsumerStats { return &ConsumerStats{ MessagesReceived: atomic.LoadUint64(&r.messagesReceived), MessagesFinished: atomic.LoadUint64(&r.messagesFinished), MessagesRequeued: atomic.LoadUint64(&r.messagesRequeued), Connections: len(r.conns()), } }
[ "func", "(", "r", "*", "Consumer", ")", "Stats", "(", ")", "*", "ConsumerStats", "{", "return", "&", "ConsumerStats", "{", "MessagesReceived", ":", "atomic", ".", "LoadUint64", "(", "&", "r", ".", "messagesReceived", ")", ",", "MessagesFinished", ":", "ato...
// Stats retrieves the current connection and message statistics for a Consumer
[ "Stats", "retrieves", "the", "current", "connection", "and", "message", "statistics", "for", "a", "Consumer" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L192-L199
train
nsqio/go-nsq
consumer.go
perConnMaxInFlight
func (r *Consumer) perConnMaxInFlight() int64 { b := float64(r.getMaxInFlight()) s := b / float64(len(r.conns())) return int64(math.Min(math.Max(1, s), b)) }
go
func (r *Consumer) perConnMaxInFlight() int64 { b := float64(r.getMaxInFlight()) s := b / float64(len(r.conns())) return int64(math.Min(math.Max(1, s), b)) }
[ "func", "(", "r", "*", "Consumer", ")", "perConnMaxInFlight", "(", ")", "int64", "{", "b", ":=", "float64", "(", "r", ".", "getMaxInFlight", "(", ")", ")", "\n", "s", ":=", "b", "/", "float64", "(", "len", "(", "r", ".", "conns", "(", ")", ")", ...
// perConnMaxInFlight calculates the per-connection max-in-flight count. // // This may change dynamically based on the number of connections to nsqd the Consumer // is responsible for.
[ "perConnMaxInFlight", "calculates", "the", "per", "-", "connection", "max", "-", "in", "-", "flight", "count", ".", "This", "may", "change", "dynamically", "based", "on", "the", "number", "of", "connections", "to", "nsqd", "the", "Consumer", "is", "responsible...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L257-L261
train
nsqio/go-nsq
consumer.go
ConnectToNSQLookupd
func (r *Consumer) ConnectToNSQLookupd(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } if err := validatedLookupAddr(addr); err != nil { return err } atomic.StoreInt32(&r.connectedFlag, 1) r.mtx.Lock() for _, x := range r.lookupdHTTPAddrs { if x == addr { r.mtx.Unlock() return nil } } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs, addr) numLookupd := len(r.lookupdHTTPAddrs) r.mtx.Unlock() // if this is the first one, kick off the go loop if numLookupd == 1 { r.queryLookupd() r.wg.Add(1) go r.lookupdLoop() } return nil }
go
func (r *Consumer) ConnectToNSQLookupd(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } if err := validatedLookupAddr(addr); err != nil { return err } atomic.StoreInt32(&r.connectedFlag, 1) r.mtx.Lock() for _, x := range r.lookupdHTTPAddrs { if x == addr { r.mtx.Unlock() return nil } } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs, addr) numLookupd := len(r.lookupdHTTPAddrs) r.mtx.Unlock() // if this is the first one, kick off the go loop if numLookupd == 1 { r.queryLookupd() r.wg.Add(1) go r.lookupdLoop() } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQLookupd", "(", "addr", "string", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "r", ".", "stopFlag", ")", "==", "1", "{", "return", "errors", ".", "New", "(", "\"consumer stopped\"", ...
// ConnectToNSQLookupd adds an nsqlookupd address to the list for this Consumer instance. // // If it is the first to be added, it initiates an HTTP request to discover nsqd // producers for the configured topic. // // A goroutine is spawned to handle continual polling.
[ "ConnectToNSQLookupd", "adds", "an", "nsqlookupd", "address", "to", "the", "list", "for", "this", "Consumer", "instance", ".", "If", "it", "is", "the", "first", "to", "be", "added", "it", "initiates", "an", "HTTP", "request", "to", "discover", "nsqd", "produ...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L304-L337
train
nsqio/go-nsq
consumer.go
ConnectToNSQLookupds
func (r *Consumer) ConnectToNSQLookupds(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQLookupd(addr) if err != nil { return err } } return nil }
go
func (r *Consumer) ConnectToNSQLookupds(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQLookupd(addr) if err != nil { return err } } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQLookupds", "(", "addresses", "[", "]", "string", ")", "error", "{", "for", "_", ",", "addr", ":=", "range", "addresses", "{", "err", ":=", "r", ".", "ConnectToNSQLookupd", "(", "addr", ")", "\n", "if...
// ConnectToNSQLookupds adds multiple nsqlookupd address to the list for this Consumer instance. // // If adding the first address it initiates an HTTP request to discover nsqd // producers for the configured topic. // // A goroutine is spawned to handle continual polling.
[ "ConnectToNSQLookupds", "adds", "multiple", "nsqlookupd", "address", "to", "the", "list", "for", "this", "Consumer", "instance", ".", "If", "adding", "the", "first", "address", "it", "initiates", "an", "HTTP", "request", "to", "discover", "nsqd", "producers", "f...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L345-L353
train
nsqio/go-nsq
consumer.go
lookupdLoop
func (r *Consumer) lookupdLoop() { // add some jitter so that multiple consumers discovering the same topic, // when restarted at the same time, dont all connect at once. r.rngMtx.Lock() jitter := time.Duration(int64(r.rng.Float64() * r.config.LookupdPollJitter * float64(r.config.LookupdPollInterval))) r.rngMtx.Unlock() var ticker *time.Ticker select { case <-time.After(jitter): case <-r.exitChan: goto exit } ticker = time.NewTicker(r.config.LookupdPollInterval) for { select { case <-ticker.C: r.queryLookupd() case <-r.lookupdRecheckChan: r.queryLookupd() case <-r.exitChan: goto exit } } exit: if ticker != nil { ticker.Stop() } r.log(LogLevelInfo, "exiting lookupdLoop") r.wg.Done() }
go
func (r *Consumer) lookupdLoop() { // add some jitter so that multiple consumers discovering the same topic, // when restarted at the same time, dont all connect at once. r.rngMtx.Lock() jitter := time.Duration(int64(r.rng.Float64() * r.config.LookupdPollJitter * float64(r.config.LookupdPollInterval))) r.rngMtx.Unlock() var ticker *time.Ticker select { case <-time.After(jitter): case <-r.exitChan: goto exit } ticker = time.NewTicker(r.config.LookupdPollInterval) for { select { case <-ticker.C: r.queryLookupd() case <-r.lookupdRecheckChan: r.queryLookupd() case <-r.exitChan: goto exit } } exit: if ticker != nil { ticker.Stop() } r.log(LogLevelInfo, "exiting lookupdLoop") r.wg.Done() }
[ "func", "(", "r", "*", "Consumer", ")", "lookupdLoop", "(", ")", "{", "r", ".", "rngMtx", ".", "Lock", "(", ")", "\n", "jitter", ":=", "time", ".", "Duration", "(", "int64", "(", "r", ".", "rng", ".", "Float64", "(", ")", "*", "r", ".", "config...
// poll all known lookup servers every LookupdPollInterval
[ "poll", "all", "known", "lookup", "servers", "every", "LookupdPollInterval" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L370-L404
train
nsqio/go-nsq
consumer.go
nextLookupdEndpoint
func (r *Consumer) nextLookupdEndpoint() string { r.mtx.RLock() if r.lookupdQueryIndex >= len(r.lookupdHTTPAddrs) { r.lookupdQueryIndex = 0 } addr := r.lookupdHTTPAddrs[r.lookupdQueryIndex] num := len(r.lookupdHTTPAddrs) r.mtx.RUnlock() r.lookupdQueryIndex = (r.lookupdQueryIndex + 1) % num urlString := addr if !strings.Contains(urlString, "://") { urlString = "http://" + addr } u, err := url.Parse(urlString) if err != nil { panic(err) } if u.Path == "/" || u.Path == "" { u.Path = "/lookup" } v, err := url.ParseQuery(u.RawQuery) v.Add("topic", r.topic) u.RawQuery = v.Encode() return u.String() }
go
func (r *Consumer) nextLookupdEndpoint() string { r.mtx.RLock() if r.lookupdQueryIndex >= len(r.lookupdHTTPAddrs) { r.lookupdQueryIndex = 0 } addr := r.lookupdHTTPAddrs[r.lookupdQueryIndex] num := len(r.lookupdHTTPAddrs) r.mtx.RUnlock() r.lookupdQueryIndex = (r.lookupdQueryIndex + 1) % num urlString := addr if !strings.Contains(urlString, "://") { urlString = "http://" + addr } u, err := url.Parse(urlString) if err != nil { panic(err) } if u.Path == "/" || u.Path == "" { u.Path = "/lookup" } v, err := url.ParseQuery(u.RawQuery) v.Add("topic", r.topic) u.RawQuery = v.Encode() return u.String() }
[ "func", "(", "r", "*", "Consumer", ")", "nextLookupdEndpoint", "(", ")", "string", "{", "r", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "r", ".", "lookupdQueryIndex", ">=", "len", "(", "r", ".", "lookupdHTTPAddrs", ")", "{", "r", ".", "lookupdQu...
// return the next lookupd endpoint to query // keeping track of which one was last used
[ "return", "the", "next", "lookupd", "endpoint", "to", "query", "keeping", "track", "of", "which", "one", "was", "last", "used" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L408-L435
train
nsqio/go-nsq
consumer.go
queryLookupd
func (r *Consumer) queryLookupd() { retries := 0 retry: endpoint := r.nextLookupdEndpoint() r.log(LogLevelInfo, "querying nsqlookupd %s", endpoint) var data lookupResp err := apiRequestNegotiateV1("GET", endpoint, nil, &data) if err != nil { r.log(LogLevelError, "error querying nsqlookupd (%s) - %s", endpoint, err) retries++ if retries < 3 { r.log(LogLevelInfo, "retrying with next nsqlookupd") goto retry } return } var nsqdAddrs []string for _, producer := range data.Producers { broadcastAddress := producer.BroadcastAddress port := producer.TCPPort joined := net.JoinHostPort(broadcastAddress, strconv.Itoa(port)) nsqdAddrs = append(nsqdAddrs, joined) } // apply filter if discoveryFilter, ok := r.behaviorDelegate.(DiscoveryFilter); ok { nsqdAddrs = discoveryFilter.Filter(nsqdAddrs) } for _, addr := range nsqdAddrs { err = r.ConnectToNSQD(addr) if err != nil && err != ErrAlreadyConnected { r.log(LogLevelError, "(%s) error connecting to nsqd - %s", addr, err) continue } } }
go
func (r *Consumer) queryLookupd() { retries := 0 retry: endpoint := r.nextLookupdEndpoint() r.log(LogLevelInfo, "querying nsqlookupd %s", endpoint) var data lookupResp err := apiRequestNegotiateV1("GET", endpoint, nil, &data) if err != nil { r.log(LogLevelError, "error querying nsqlookupd (%s) - %s", endpoint, err) retries++ if retries < 3 { r.log(LogLevelInfo, "retrying with next nsqlookupd") goto retry } return } var nsqdAddrs []string for _, producer := range data.Producers { broadcastAddress := producer.BroadcastAddress port := producer.TCPPort joined := net.JoinHostPort(broadcastAddress, strconv.Itoa(port)) nsqdAddrs = append(nsqdAddrs, joined) } // apply filter if discoveryFilter, ok := r.behaviorDelegate.(DiscoveryFilter); ok { nsqdAddrs = discoveryFilter.Filter(nsqdAddrs) } for _, addr := range nsqdAddrs { err = r.ConnectToNSQD(addr) if err != nil && err != ErrAlreadyConnected { r.log(LogLevelError, "(%s) error connecting to nsqd - %s", addr, err) continue } } }
[ "func", "(", "r", "*", "Consumer", ")", "queryLookupd", "(", ")", "{", "retries", ":=", "0", "\n", "retry", ":", "endpoint", ":=", "r", ".", "nextLookupdEndpoint", "(", ")", "\n", "r", ".", "log", "(", "LogLevelInfo", ",", "\"querying nsqlookupd %s\"", "...
// make an HTTP req to one of the configured nsqlookupd instances to discover // which nsqd's provide the topic we are consuming. // // initiate a connection to any new producers that are identified.
[ "make", "an", "HTTP", "req", "to", "one", "of", "the", "configured", "nsqlookupd", "instances", "to", "discover", "which", "nsqd", "s", "provide", "the", "topic", "we", "are", "consuming", ".", "initiate", "a", "connection", "to", "any", "new", "producers", ...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L456-L494
train
nsqio/go-nsq
consumer.go
ConnectToNSQDs
func (r *Consumer) ConnectToNSQDs(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQD(addr) if err != nil { return err } } return nil }
go
func (r *Consumer) ConnectToNSQDs(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQD(addr) if err != nil { return err } } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQDs", "(", "addresses", "[", "]", "string", ")", "error", "{", "for", "_", ",", "addr", ":=", "range", "addresses", "{", "err", ":=", "r", ".", "ConnectToNSQD", "(", "addr", ")", "\n", "if", "err", ...
// ConnectToNSQDs takes multiple nsqd addresses to connect directly to. // // It is recommended to use ConnectToNSQLookupd so that topics are discovered // automatically. This method is useful when you want to connect to local instance.
[ "ConnectToNSQDs", "takes", "multiple", "nsqd", "addresses", "to", "connect", "directly", "to", ".", "It", "is", "recommended", "to", "use", "ConnectToNSQLookupd", "so", "that", "topics", "are", "discovered", "automatically", ".", "This", "method", "is", "useful", ...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L500-L508
train
nsqio/go-nsq
consumer.go
ConnectToNSQD
func (r *Consumer) ConnectToNSQD(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } atomic.StoreInt32(&r.connectedFlag, 1) logger, logLvl := r.getLogger() conn := NewConn(addr, &r.config, &consumerConnDelegate{r}) conn.SetLogger(logger, logLvl, fmt.Sprintf("%3d [%s/%s] (%%s)", r.id, r.topic, r.channel)) r.mtx.Lock() _, pendingOk := r.pendingConnections[addr] _, ok := r.connections[addr] if ok || pendingOk { r.mtx.Unlock() return ErrAlreadyConnected } r.pendingConnections[addr] = conn if idx := indexOf(addr, r.nsqdTCPAddrs); idx == -1 { r.nsqdTCPAddrs = append(r.nsqdTCPAddrs, addr) } r.mtx.Unlock() r.log(LogLevelInfo, "(%s) connecting to nsqd", addr) cleanupConnection := func() { r.mtx.Lock() delete(r.pendingConnections, addr) r.mtx.Unlock() conn.Close() } resp, err := conn.Connect() if err != nil { cleanupConnection() return err } if resp != nil { if resp.MaxRdyCount < int64(r.getMaxInFlight()) { r.log(LogLevelWarning, "(%s) max RDY count %d < consumer max in flight %d, truncation possible", conn.String(), resp.MaxRdyCount, r.getMaxInFlight()) } } cmd := Subscribe(r.topic, r.channel) err = conn.WriteCommand(cmd) if err != nil { cleanupConnection() return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s", conn, r.topic, r.channel, err.Error()) } r.mtx.Lock() delete(r.pendingConnections, addr) r.connections[addr] = conn r.mtx.Unlock() // pre-emptive signal to existing connections to lower their RDY count for _, c := range r.conns() { r.maybeUpdateRDY(c) } return nil }
go
func (r *Consumer) ConnectToNSQD(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } atomic.StoreInt32(&r.connectedFlag, 1) logger, logLvl := r.getLogger() conn := NewConn(addr, &r.config, &consumerConnDelegate{r}) conn.SetLogger(logger, logLvl, fmt.Sprintf("%3d [%s/%s] (%%s)", r.id, r.topic, r.channel)) r.mtx.Lock() _, pendingOk := r.pendingConnections[addr] _, ok := r.connections[addr] if ok || pendingOk { r.mtx.Unlock() return ErrAlreadyConnected } r.pendingConnections[addr] = conn if idx := indexOf(addr, r.nsqdTCPAddrs); idx == -1 { r.nsqdTCPAddrs = append(r.nsqdTCPAddrs, addr) } r.mtx.Unlock() r.log(LogLevelInfo, "(%s) connecting to nsqd", addr) cleanupConnection := func() { r.mtx.Lock() delete(r.pendingConnections, addr) r.mtx.Unlock() conn.Close() } resp, err := conn.Connect() if err != nil { cleanupConnection() return err } if resp != nil { if resp.MaxRdyCount < int64(r.getMaxInFlight()) { r.log(LogLevelWarning, "(%s) max RDY count %d < consumer max in flight %d, truncation possible", conn.String(), resp.MaxRdyCount, r.getMaxInFlight()) } } cmd := Subscribe(r.topic, r.channel) err = conn.WriteCommand(cmd) if err != nil { cleanupConnection() return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s", conn, r.topic, r.channel, err.Error()) } r.mtx.Lock() delete(r.pendingConnections, addr) r.connections[addr] = conn r.mtx.Unlock() // pre-emptive signal to existing connections to lower their RDY count for _, c := range r.conns() { r.maybeUpdateRDY(c) } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQD", "(", "addr", "string", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "r", ".", "stopFlag", ")", "==", "1", "{", "return", "errors", ".", "New", "(", "\"consumer stopped\"", ")", ...
// ConnectToNSQD takes a nsqd address to connect directly to. // // It is recommended to use ConnectToNSQLookupd so that topics are discovered // automatically. This method is useful when you want to connect to a single, local, // instance.
[ "ConnectToNSQD", "takes", "a", "nsqd", "address", "to", "connect", "directly", "to", ".", "It", "is", "recommended", "to", "use", "ConnectToNSQLookupd", "so", "that", "topics", "are", "discovered", "automatically", ".", "This", "method", "is", "useful", "when", ...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L515-L587
train
nsqio/go-nsq
consumer.go
DisconnectFromNSQD
func (r *Consumer) DisconnectFromNSQD(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.nsqdTCPAddrs) if idx == -1 { return ErrNotConnected } // slice delete r.nsqdTCPAddrs = append(r.nsqdTCPAddrs[:idx], r.nsqdTCPAddrs[idx+1:]...) pendingConn, pendingOk := r.pendingConnections[addr] conn, ok := r.connections[addr] if ok { conn.Close() } else if pendingOk { pendingConn.Close() } return nil }
go
func (r *Consumer) DisconnectFromNSQD(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.nsqdTCPAddrs) if idx == -1 { return ErrNotConnected } // slice delete r.nsqdTCPAddrs = append(r.nsqdTCPAddrs[:idx], r.nsqdTCPAddrs[idx+1:]...) pendingConn, pendingOk := r.pendingConnections[addr] conn, ok := r.connections[addr] if ok { conn.Close() } else if pendingOk { pendingConn.Close() } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "DisconnectFromNSQD", "(", "addr", "string", ")", "error", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "idx", ":=", "indexOf", "(", "addr", ",...
// DisconnectFromNSQD closes the connection to and removes the specified // `nsqd` address from the list
[ "DisconnectFromNSQD", "closes", "the", "connection", "to", "and", "removes", "the", "specified", "nsqd", "address", "from", "the", "list" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L600-L622
train
nsqio/go-nsq
consumer.go
DisconnectFromNSQLookupd
func (r *Consumer) DisconnectFromNSQLookupd(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.lookupdHTTPAddrs) if idx == -1 { return ErrNotConnected } if len(r.lookupdHTTPAddrs) == 1 { return fmt.Errorf("cannot disconnect from only remaining nsqlookupd HTTP address %s", addr) } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs[:idx], r.lookupdHTTPAddrs[idx+1:]...) return nil }
go
func (r *Consumer) DisconnectFromNSQLookupd(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.lookupdHTTPAddrs) if idx == -1 { return ErrNotConnected } if len(r.lookupdHTTPAddrs) == 1 { return fmt.Errorf("cannot disconnect from only remaining nsqlookupd HTTP address %s", addr) } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs[:idx], r.lookupdHTTPAddrs[idx+1:]...) return nil }
[ "func", "(", "r", "*", "Consumer", ")", "DisconnectFromNSQLookupd", "(", "addr", "string", ")", "error", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "idx", ":=", "indexOf", "(", "addr"...
// DisconnectFromNSQLookupd removes the specified `nsqlookupd` address // from the list used for periodic discovery.
[ "DisconnectFromNSQLookupd", "removes", "the", "specified", "nsqlookupd", "address", "from", "the", "list", "used", "for", "periodic", "discovery", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L626-L642
train
nsqio/go-nsq
message.go
Finish
func (m *Message) Finish() { if !atomic.CompareAndSwapInt32(&m.responded, 0, 1) { return } m.Delegate.OnFinish(m) }
go
func (m *Message) Finish() { if !atomic.CompareAndSwapInt32(&m.responded, 0, 1) { return } m.Delegate.OnFinish(m) }
[ "func", "(", "m", "*", "Message", ")", "Finish", "(", ")", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "m", ".", "responded", ",", "0", ",", "1", ")", "{", "return", "\n", "}", "\n", "m", ".", "Delegate", ".", "OnFinish", "(",...
// Finish sends a FIN command to the nsqd which // sent this message
[ "Finish", "sends", "a", "FIN", "command", "to", "the", "nsqd", "which", "sent", "this", "message" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/message.go#L66-L71
train
nsqio/go-nsq
message.go
Requeue
func (m *Message) Requeue(delay time.Duration) { m.doRequeue(delay, true) }
go
func (m *Message) Requeue(delay time.Duration) { m.doRequeue(delay, true) }
[ "func", "(", "m", "*", "Message", ")", "Requeue", "(", "delay", "time", ".", "Duration", ")", "{", "m", ".", "doRequeue", "(", "delay", ",", "true", ")", "\n", "}" ]
// Requeue sends a REQ command to the nsqd which // sent this message, using the supplied delay. // // A delay of -1 will automatically calculate // based on the number of attempts and the // configured default_requeue_delay
[ "Requeue", "sends", "a", "REQ", "command", "to", "the", "nsqd", "which", "sent", "this", "message", "using", "the", "supplied", "delay", ".", "A", "delay", "of", "-", "1", "will", "automatically", "calculate", "based", "on", "the", "number", "of", "attempt...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/message.go#L88-L90
train
nsqio/go-nsq
message.go
RequeueWithoutBackoff
func (m *Message) RequeueWithoutBackoff(delay time.Duration) { m.doRequeue(delay, false) }
go
func (m *Message) RequeueWithoutBackoff(delay time.Duration) { m.doRequeue(delay, false) }
[ "func", "(", "m", "*", "Message", ")", "RequeueWithoutBackoff", "(", "delay", "time", ".", "Duration", ")", "{", "m", ".", "doRequeue", "(", "delay", ",", "false", ")", "\n", "}" ]
// RequeueWithoutBackoff sends a REQ command to the nsqd which // sent this message, using the supplied delay. // // Notably, using this method to respond does not trigger a backoff // event on the configured Delegate.
[ "RequeueWithoutBackoff", "sends", "a", "REQ", "command", "to", "the", "nsqd", "which", "sent", "this", "message", "using", "the", "supplied", "delay", ".", "Notably", "using", "this", "method", "to", "respond", "does", "not", "trigger", "a", "backoff", "event"...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/message.go#L97-L99
train
nsqio/go-nsq
producer.go
Publish
func (w *Producer) Publish(topic string, body []byte) error { return w.sendCommand(Publish(topic, body)) }
go
func (w *Producer) Publish(topic string, body []byte) error { return w.sendCommand(Publish(topic, body)) }
[ "func", "(", "w", "*", "Producer", ")", "Publish", "(", "topic", "string", ",", "body", "[", "]", "byte", ")", "error", "{", "return", "w", ".", "sendCommand", "(", "Publish", "(", "topic", ",", "body", ")", ")", "\n", "}" ]
// Publish synchronously publishes a message body to the specified topic, returning // an error if publish failed
[ "Publish", "synchronously", "publishes", "a", "message", "body", "to", "the", "specified", "topic", "returning", "an", "error", "if", "publish", "failed" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/producer.go#L184-L186
train
nsqio/go-nsq
producer.go
MultiPublish
func (w *Producer) MultiPublish(topic string, body [][]byte) error { cmd, err := MultiPublish(topic, body) if err != nil { return err } return w.sendCommand(cmd) }
go
func (w *Producer) MultiPublish(topic string, body [][]byte) error { cmd, err := MultiPublish(topic, body) if err != nil { return err } return w.sendCommand(cmd) }
[ "func", "(", "w", "*", "Producer", ")", "MultiPublish", "(", "topic", "string", ",", "body", "[", "]", "[", "]", "byte", ")", "error", "{", "cmd", ",", "err", ":=", "MultiPublish", "(", "topic", ",", "body", ")", "\n", "if", "err", "!=", "nil", "...
// MultiPublish synchronously publishes a slice of message bodies to the specified topic, returning // an error if publish failed
[ "MultiPublish", "synchronously", "publishes", "a", "slice", "of", "message", "bodies", "to", "the", "specified", "topic", "returning", "an", "error", "if", "publish", "failed" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/producer.go#L190-L196
train
nsqio/go-nsq
producer.go
DeferredPublish
func (w *Producer) DeferredPublish(topic string, delay time.Duration, body []byte) error { return w.sendCommand(DeferredPublish(topic, delay, body)) }
go
func (w *Producer) DeferredPublish(topic string, delay time.Duration, body []byte) error { return w.sendCommand(DeferredPublish(topic, delay, body)) }
[ "func", "(", "w", "*", "Producer", ")", "DeferredPublish", "(", "topic", "string", ",", "delay", "time", ".", "Duration", ",", "body", "[", "]", "byte", ")", "error", "{", "return", "w", ".", "sendCommand", "(", "DeferredPublish", "(", "topic", ",", "d...
// DeferredPublish synchronously publishes a message body to the specified topic // where the message will queue at the channel level until the timeout expires, returning // an error if publish failed
[ "DeferredPublish", "synchronously", "publishes", "a", "message", "body", "to", "the", "specified", "topic", "where", "the", "message", "will", "queue", "at", "the", "channel", "level", "until", "the", "timeout", "expires", "returning", "an", "error", "if", "publ...
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/producer.go#L201-L203
train
goftp/server
listformatter.go
Short
func (formatter listFormatter) Short() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
go
func (formatter listFormatter) Short() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
[ "func", "(", "formatter", "listFormatter", ")", "Short", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "file", ":=", "range", "formatter", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"%s\\r\\n\"...
// Short returns a string that lists the collection of files by name only, // one per line
[ "Short", "returns", "a", "string", "that", "lists", "the", "collection", "of", "files", "by", "name", "only", "one", "per", "line" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/listformatter.go#L18-L24
train
goftp/server
listformatter.go
Detailed
func (formatter listFormatter) Detailed() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, file.Mode().String()) fmt.Fprintf(&buf, " 1 %s %s ", file.Owner(), file.Group()) fmt.Fprintf(&buf, lpad(strconv.FormatInt(file.Size(), 10), 12)) fmt.Fprintf(&buf, file.ModTime().Format(" Jan _2 15:04 ")) fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
go
func (formatter listFormatter) Detailed() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, file.Mode().String()) fmt.Fprintf(&buf, " 1 %s %s ", file.Owner(), file.Group()) fmt.Fprintf(&buf, lpad(strconv.FormatInt(file.Size(), 10), 12)) fmt.Fprintf(&buf, file.ModTime().Format(" Jan _2 15:04 ")) fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
[ "func", "(", "formatter", "listFormatter", ")", "Detailed", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "file", ":=", "range", "formatter", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "file", ...
// Detailed returns a string that lists the collection of files with extra // detail, one per line
[ "Detailed", "returns", "a", "string", "that", "lists", "the", "collection", "of", "files", "with", "extra", "detail", "one", "per", "line" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/listformatter.go#L28-L38
train
goftp/server
auth.go
CheckPasswd
func (a *SimpleAuth) CheckPasswd(name, pass string) (bool, error) { if name != a.Name || pass != a.Password { return false, nil } return true, nil }
go
func (a *SimpleAuth) CheckPasswd(name, pass string) (bool, error) { if name != a.Name || pass != a.Password { return false, nil } return true, nil }
[ "func", "(", "a", "*", "SimpleAuth", ")", "CheckPasswd", "(", "name", ",", "pass", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "name", "!=", "a", ".", "Name", "||", "pass", "!=", "a", ".", "Password", "{", "return", "false", ",", "n...
// CheckPasswd will check user's password
[ "CheckPasswd", "will", "check", "user", "s", "password" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/auth.go#L23-L28
train
goftp/server
server.go
serverOptsWithDefaults
func serverOptsWithDefaults(opts *ServerOpts) *ServerOpts { var newOpts ServerOpts if opts == nil { opts = &ServerOpts{} } if opts.Hostname == "" { newOpts.Hostname = "::" } else { newOpts.Hostname = opts.Hostname } if opts.Port == 0 { newOpts.Port = 3000 } else { newOpts.Port = opts.Port } newOpts.Factory = opts.Factory if opts.Name == "" { newOpts.Name = "Go FTP Server" } else { newOpts.Name = opts.Name } if opts.WelcomeMessage == "" { newOpts.WelcomeMessage = defaultWelcomeMessage } else { newOpts.WelcomeMessage = opts.WelcomeMessage } if opts.Auth != nil { newOpts.Auth = opts.Auth } newOpts.Logger = &StdLogger{} if opts.Logger != nil { newOpts.Logger = opts.Logger } newOpts.TLS = opts.TLS newOpts.KeyFile = opts.KeyFile newOpts.CertFile = opts.CertFile newOpts.ExplicitFTPS = opts.ExplicitFTPS newOpts.PublicIp = opts.PublicIp newOpts.PassivePorts = opts.PassivePorts return &newOpts }
go
func serverOptsWithDefaults(opts *ServerOpts) *ServerOpts { var newOpts ServerOpts if opts == nil { opts = &ServerOpts{} } if opts.Hostname == "" { newOpts.Hostname = "::" } else { newOpts.Hostname = opts.Hostname } if opts.Port == 0 { newOpts.Port = 3000 } else { newOpts.Port = opts.Port } newOpts.Factory = opts.Factory if opts.Name == "" { newOpts.Name = "Go FTP Server" } else { newOpts.Name = opts.Name } if opts.WelcomeMessage == "" { newOpts.WelcomeMessage = defaultWelcomeMessage } else { newOpts.WelcomeMessage = opts.WelcomeMessage } if opts.Auth != nil { newOpts.Auth = opts.Auth } newOpts.Logger = &StdLogger{} if opts.Logger != nil { newOpts.Logger = opts.Logger } newOpts.TLS = opts.TLS newOpts.KeyFile = opts.KeyFile newOpts.CertFile = opts.CertFile newOpts.ExplicitFTPS = opts.ExplicitFTPS newOpts.PublicIp = opts.PublicIp newOpts.PassivePorts = opts.PassivePorts return &newOpts }
[ "func", "serverOptsWithDefaults", "(", "opts", "*", "ServerOpts", ")", "*", "ServerOpts", "{", "var", "newOpts", "ServerOpts", "\n", "if", "opts", "==", "nil", "{", "opts", "=", "&", "ServerOpts", "{", "}", "\n", "}", "\n", "if", "opts", ".", "Hostname",...
// serverOptsWithDefaults copies an ServerOpts struct into a new struct, // then adds any default values that are missing and returns the new data.
[ "serverOptsWithDefaults", "copies", "an", "ServerOpts", "struct", "into", "a", "new", "struct", "then", "adds", "any", "default", "values", "that", "are", "missing", "and", "returns", "the", "new", "data", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L86-L132
train
goftp/server
server.go
newConn
func (server *Server) newConn(tcpConn net.Conn, driver Driver) *Conn { c := new(Conn) c.namePrefix = "/" c.conn = tcpConn c.controlReader = bufio.NewReader(tcpConn) c.controlWriter = bufio.NewWriter(tcpConn) c.driver = driver c.auth = server.Auth c.server = server c.sessionID = newSessionID() c.logger = server.logger c.tlsConfig = server.tlsConfig driver.Init(c) return c }
go
func (server *Server) newConn(tcpConn net.Conn, driver Driver) *Conn { c := new(Conn) c.namePrefix = "/" c.conn = tcpConn c.controlReader = bufio.NewReader(tcpConn) c.controlWriter = bufio.NewWriter(tcpConn) c.driver = driver c.auth = server.Auth c.server = server c.sessionID = newSessionID() c.logger = server.logger c.tlsConfig = server.tlsConfig driver.Init(c) return c }
[ "func", "(", "server", "*", "Server", ")", "newConn", "(", "tcpConn", "net", ".", "Conn", ",", "driver", "Driver", ")", "*", "Conn", "{", "c", ":=", "new", "(", "Conn", ")", "\n", "c", ".", "namePrefix", "=", "\"/\"", "\n", "c", ".", "conn", "=",...
// NewConn constructs a new object that will handle the FTP protocol over // an active net.TCPConn. The TCP connection should already be open before // it is handed to this functions. driver is an instance of FTPDriver that // will handle all auth and persistence details.
[ "NewConn", "constructs", "a", "new", "object", "that", "will", "handle", "the", "FTP", "protocol", "over", "an", "active", "net", ".", "TCPConn", ".", "The", "TCP", "connection", "should", "already", "be", "open", "before", "it", "is", "handed", "to", "thi...
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L164-L179
train
goftp/server
server.go
ListenAndServe
func (server *Server) ListenAndServe() error { var listener net.Listener var err error var curFeats = featCmds if server.ServerOpts.TLS { server.tlsConfig, err = simpleTLSConfig(server.CertFile, server.KeyFile) if err != nil { return err } curFeats += " AUTH TLS\n PBSZ\n PROT\n" if server.ServerOpts.ExplicitFTPS { listener, err = net.Listen("tcp", server.listenTo) } else { listener, err = tls.Listen("tcp", server.listenTo, server.tlsConfig) } } else { listener, err = net.Listen("tcp", server.listenTo) } if err != nil { return err } server.feats = fmt.Sprintf(feats, curFeats) sessionID := "" server.logger.Printf(sessionID, "%s listening on %d", server.Name, server.Port) return server.Serve(listener) }
go
func (server *Server) ListenAndServe() error { var listener net.Listener var err error var curFeats = featCmds if server.ServerOpts.TLS { server.tlsConfig, err = simpleTLSConfig(server.CertFile, server.KeyFile) if err != nil { return err } curFeats += " AUTH TLS\n PBSZ\n PROT\n" if server.ServerOpts.ExplicitFTPS { listener, err = net.Listen("tcp", server.listenTo) } else { listener, err = tls.Listen("tcp", server.listenTo, server.tlsConfig) } } else { listener, err = net.Listen("tcp", server.listenTo) } if err != nil { return err } server.feats = fmt.Sprintf(feats, curFeats) sessionID := "" server.logger.Printf(sessionID, "%s listening on %d", server.Name, server.Port) return server.Serve(listener) }
[ "func", "(", "server", "*", "Server", ")", "ListenAndServe", "(", ")", "error", "{", "var", "listener", "net", ".", "Listener", "\n", "var", "err", "error", "\n", "var", "curFeats", "=", "featCmds", "\n", "if", "server", ".", "ServerOpts", ".", "TLS", ...
// ListenAndServe asks a new Server to begin accepting client connections. It // accepts no arguments - all configuration is provided via the NewServer // function. // // If the server fails to start for any reason, an error will be returned. Common // errors are trying to bind to a privileged port or something else is already // listening on the same port. //
[ "ListenAndServe", "asks", "a", "new", "Server", "to", "begin", "accepting", "client", "connections", ".", "It", "accepts", "no", "arguments", "-", "all", "configuration", "is", "provided", "via", "the", "NewServer", "function", ".", "If", "the", "server", "fai...
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L204-L234
train
goftp/server
server.go
Serve
func (server *Server) Serve(l net.Listener) error { server.listener = l server.ctx, server.cancel = context.WithCancel(context.Background()) sessionID := "" for { tcpConn, err := server.listener.Accept() if err != nil { select { case <-server.ctx.Done(): return ErrServerClosed default: } server.logger.Printf(sessionID, "listening error: %v", err) if ne, ok := err.(net.Error); ok && ne.Temporary() { continue } return err } driver, err := server.Factory.NewDriver() if err != nil { server.logger.Printf(sessionID, "Error creating driver, aborting client connection: %v", err) tcpConn.Close() } else { ftpConn := server.newConn(tcpConn, driver) go ftpConn.Serve() } } }
go
func (server *Server) Serve(l net.Listener) error { server.listener = l server.ctx, server.cancel = context.WithCancel(context.Background()) sessionID := "" for { tcpConn, err := server.listener.Accept() if err != nil { select { case <-server.ctx.Done(): return ErrServerClosed default: } server.logger.Printf(sessionID, "listening error: %v", err) if ne, ok := err.(net.Error); ok && ne.Temporary() { continue } return err } driver, err := server.Factory.NewDriver() if err != nil { server.logger.Printf(sessionID, "Error creating driver, aborting client connection: %v", err) tcpConn.Close() } else { ftpConn := server.newConn(tcpConn, driver) go ftpConn.Serve() } } }
[ "func", "(", "server", "*", "Server", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "server", ".", "listener", "=", "l", "\n", "server", ".", "ctx", ",", "server", ".", "cancel", "=", "context", ".", "WithCancel", "(", "context",...
// Serve accepts connections on a given net.Listener and handles each // request in a new goroutine. //
[ "Serve", "accepts", "connections", "on", "a", "given", "net", ".", "Listener", "and", "handles", "each", "request", "in", "a", "new", "goroutine", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L239-L266
train
goftp/server
server.go
Shutdown
func (server *Server) Shutdown() error { if server.cancel != nil { server.cancel() } if server.listener != nil { return server.listener.Close() } // server wasnt even started return nil }
go
func (server *Server) Shutdown() error { if server.cancel != nil { server.cancel() } if server.listener != nil { return server.listener.Close() } // server wasnt even started return nil }
[ "func", "(", "server", "*", "Server", ")", "Shutdown", "(", ")", "error", "{", "if", "server", ".", "cancel", "!=", "nil", "{", "server", ".", "cancel", "(", ")", "\n", "}", "\n", "if", "server", ".", "listener", "!=", "nil", "{", "return", "server...
// Shutdown will gracefully stop a server. Already connected clients will retain their connections
[ "Shutdown", "will", "gracefully", "stop", "a", "server", ".", "Already", "connected", "clients", "will", "retain", "their", "connections" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L269-L278
train
goftp/server
conn.go
newSessionID
func newSessionID() string { hash := sha256.New() _, err := io.CopyN(hash, rand.Reader, 50) if err != nil { return "????????????????????" } md := hash.Sum(nil) mdStr := hex.EncodeToString(md) return mdStr[0:20] }
go
func newSessionID() string { hash := sha256.New() _, err := io.CopyN(hash, rand.Reader, 50) if err != nil { return "????????????????????" } md := hash.Sum(nil) mdStr := hex.EncodeToString(md) return mdStr[0:20] }
[ "func", "newSessionID", "(", ")", "string", "{", "hash", ":=", "sha256", ".", "New", "(", ")", "\n", "_", ",", "err", ":=", "io", ".", "CopyN", "(", "hash", ",", "rand", ".", "Reader", ",", "50", ")", "\n", "if", "err", "!=", "nil", "{", "retur...
// returns a random 20 char string that can be used as a unique session ID
[ "returns", "a", "random", "20", "char", "string", "that", "can", "be", "used", "as", "a", "unique", "session", "ID" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L86-L95
train
goftp/server
conn.go
Serve
func (conn *Conn) Serve() { conn.logger.Print(conn.sessionID, "Connection Established") // send welcome conn.writeMessage(220, conn.server.WelcomeMessage) // read commands for { line, err := conn.controlReader.ReadString('\n') if err != nil { if err != io.EOF { conn.logger.Print(conn.sessionID, fmt.Sprint("read error:", err)) } break } conn.receiveLine(line) // QUIT command closes connection, break to avoid error on reading from // closed socket if conn.closed == true { break } } conn.Close() conn.logger.Print(conn.sessionID, "Connection Terminated") }
go
func (conn *Conn) Serve() { conn.logger.Print(conn.sessionID, "Connection Established") // send welcome conn.writeMessage(220, conn.server.WelcomeMessage) // read commands for { line, err := conn.controlReader.ReadString('\n') if err != nil { if err != io.EOF { conn.logger.Print(conn.sessionID, fmt.Sprint("read error:", err)) } break } conn.receiveLine(line) // QUIT command closes connection, break to avoid error on reading from // closed socket if conn.closed == true { break } } conn.Close() conn.logger.Print(conn.sessionID, "Connection Terminated") }
[ "func", "(", "conn", "*", "Conn", ")", "Serve", "(", ")", "{", "conn", ".", "logger", ".", "Print", "(", "conn", ".", "sessionID", ",", "\"Connection Established\"", ")", "\n", "conn", ".", "writeMessage", "(", "220", ",", "conn", ".", "server", ".", ...
// Serve starts an endless loop that reads FTP commands from the client and // responds appropriately. terminated is a channel that will receive a true // message when the connection closes. This loop will be running inside a // goroutine, so use this channel to be notified when the connection can be // cleaned up.
[ "Serve", "starts", "an", "endless", "loop", "that", "reads", "FTP", "commands", "from", "the", "client", "and", "responds", "appropriately", ".", "terminated", "is", "a", "channel", "that", "will", "receive", "a", "true", "message", "when", "the", "connection"...
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L102-L125
train
goftp/server
conn.go
Close
func (conn *Conn) Close() { conn.conn.Close() conn.closed = true if conn.dataConn != nil { conn.dataConn.Close() conn.dataConn = nil } }
go
func (conn *Conn) Close() { conn.conn.Close() conn.closed = true if conn.dataConn != nil { conn.dataConn.Close() conn.dataConn = nil } }
[ "func", "(", "conn", "*", "Conn", ")", "Close", "(", ")", "{", "conn", ".", "conn", ".", "Close", "(", ")", "\n", "conn", ".", "closed", "=", "true", "\n", "if", "conn", ".", "dataConn", "!=", "nil", "{", "conn", ".", "dataConn", ".", "Close", ...
// Close will manually close this connection, even if the client isn't ready.
[ "Close", "will", "manually", "close", "this", "connection", "even", "if", "the", "client", "isn", "t", "ready", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L128-L135
train
goftp/server
conn.go
receiveLine
func (conn *Conn) receiveLine(line string) { command, param := conn.parseLine(line) conn.logger.PrintCommand(conn.sessionID, command, param) cmdObj := commands[strings.ToUpper(command)] if cmdObj == nil { conn.writeMessage(500, "Command not found") return } if cmdObj.RequireParam() && param == "" { conn.writeMessage(553, "action aborted, required param missing") } else if cmdObj.RequireAuth() && conn.user == "" { conn.writeMessage(530, "not logged in") } else { cmdObj.Execute(conn, param) } }
go
func (conn *Conn) receiveLine(line string) { command, param := conn.parseLine(line) conn.logger.PrintCommand(conn.sessionID, command, param) cmdObj := commands[strings.ToUpper(command)] if cmdObj == nil { conn.writeMessage(500, "Command not found") return } if cmdObj.RequireParam() && param == "" { conn.writeMessage(553, "action aborted, required param missing") } else if cmdObj.RequireAuth() && conn.user == "" { conn.writeMessage(530, "not logged in") } else { cmdObj.Execute(conn, param) } }
[ "func", "(", "conn", "*", "Conn", ")", "receiveLine", "(", "line", "string", ")", "{", "command", ",", "param", ":=", "conn", ".", "parseLine", "(", "line", ")", "\n", "conn", ".", "logger", ".", "PrintCommand", "(", "conn", ".", "sessionID", ",", "c...
// receiveLine accepts a single line FTP command and co-ordinates an // appropriate response.
[ "receiveLine", "accepts", "a", "single", "line", "FTP", "command", "and", "co", "-", "ordinates", "an", "appropriate", "response", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L152-L167
train
goftp/server
conn.go
writeMessage
func (conn *Conn) writeMessage(code int, message string) (wrote int, err error) { conn.logger.PrintResponse(conn.sessionID, code, message) line := fmt.Sprintf("%d %s\r\n", code, message) wrote, err = conn.controlWriter.WriteString(line) conn.controlWriter.Flush() return }
go
func (conn *Conn) writeMessage(code int, message string) (wrote int, err error) { conn.logger.PrintResponse(conn.sessionID, code, message) line := fmt.Sprintf("%d %s\r\n", code, message) wrote, err = conn.controlWriter.WriteString(line) conn.controlWriter.Flush() return }
[ "func", "(", "conn", "*", "Conn", ")", "writeMessage", "(", "code", "int", ",", "message", "string", ")", "(", "wrote", "int", ",", "err", "error", ")", "{", "conn", ".", "logger", ".", "PrintResponse", "(", "conn", ".", "sessionID", ",", "code", ","...
// writeMessage will send a standard FTP response back to the client.
[ "writeMessage", "will", "send", "a", "standard", "FTP", "response", "back", "to", "the", "client", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L178-L184
train
goftp/server
conn.go
sendOutofbandData
func (conn *Conn) sendOutofbandData(data []byte) { bytes := len(data) if conn.dataConn != nil { conn.dataConn.Write(data) conn.dataConn.Close() conn.dataConn = nil } message := "Closing data connection, sent " + strconv.Itoa(bytes) + " bytes" conn.writeMessage(226, message) }
go
func (conn *Conn) sendOutofbandData(data []byte) { bytes := len(data) if conn.dataConn != nil { conn.dataConn.Write(data) conn.dataConn.Close() conn.dataConn = nil } message := "Closing data connection, sent " + strconv.Itoa(bytes) + " bytes" conn.writeMessage(226, message) }
[ "func", "(", "conn", "*", "Conn", ")", "sendOutofbandData", "(", "data", "[", "]", "byte", ")", "{", "bytes", ":=", "len", "(", "data", ")", "\n", "if", "conn", ".", "dataConn", "!=", "nil", "{", "conn", ".", "dataConn", ".", "Write", "(", "data", ...
// sendOutofbandData will send a string to the client via the currently open // data socket. Assumes the socket is open and ready to be used.
[ "sendOutofbandData", "will", "send", "a", "string", "to", "the", "client", "via", "the", "currently", "open", "data", "socket", ".", "Assumes", "the", "socket", "is", "open", "and", "ready", "to", "be", "used", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L227-L236
train
c-bata/go-prompt
completer/file.go
Complete
func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest { if c.fileListCache == nil { c.fileListCache = make(map[string][]prompt.Suggest, 4) } path := d.GetWordBeforeCursor() dir, base, err := cleanFilePath(path) if err != nil { debug.Log("completer: cannot get current user:" + err.Error()) return nil } if cached, ok := c.fileListCache[dir]; ok { return prompt.FilterHasPrefix(cached, base, c.IgnoreCase) } files, err := ioutil.ReadDir(dir) if err != nil && os.IsNotExist(err) { return nil } else if err != nil { debug.Log("completer: cannot read directory items:" + err.Error()) return nil } suggests := make([]prompt.Suggest, 0, len(files)) for _, f := range files { if c.Filter != nil && !c.Filter(f) { continue } suggests = append(suggests, prompt.Suggest{Text: f.Name()}) } c.fileListCache[dir] = suggests return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase) }
go
func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest { if c.fileListCache == nil { c.fileListCache = make(map[string][]prompt.Suggest, 4) } path := d.GetWordBeforeCursor() dir, base, err := cleanFilePath(path) if err != nil { debug.Log("completer: cannot get current user:" + err.Error()) return nil } if cached, ok := c.fileListCache[dir]; ok { return prompt.FilterHasPrefix(cached, base, c.IgnoreCase) } files, err := ioutil.ReadDir(dir) if err != nil && os.IsNotExist(err) { return nil } else if err != nil { debug.Log("completer: cannot read directory items:" + err.Error()) return nil } suggests := make([]prompt.Suggest, 0, len(files)) for _, f := range files { if c.Filter != nil && !c.Filter(f) { continue } suggests = append(suggests, prompt.Suggest{Text: f.Name()}) } c.fileListCache[dir] = suggests return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase) }
[ "func", "(", "c", "*", "FilePathCompleter", ")", "Complete", "(", "d", "prompt", ".", "Document", ")", "[", "]", "prompt", ".", "Suggest", "{", "if", "c", ".", "fileListCache", "==", "nil", "{", "c", ".", "fileListCache", "=", "make", "(", "map", "["...
// Complete returns suggestions from your local file system.
[ "Complete", "returns", "suggestions", "from", "your", "local", "file", "system", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/completer/file.go#L57-L90
train
c-bata/go-prompt
internal/bisect/bisect.go
Right
func Right(a []int, v int) int { return bisectRightRange(a, v, 0, len(a)) }
go
func Right(a []int, v int) int { return bisectRightRange(a, v, 0, len(a)) }
[ "func", "Right", "(", "a", "[", "]", "int", ",", "v", "int", ")", "int", "{", "return", "bisectRightRange", "(", "a", ",", "v", ",", "0", ",", "len", "(", "a", ")", ")", "\n", "}" ]
// Right to locate the insertion point for v in a to maintain sorted order.
[ "Right", "to", "locate", "the", "insertion", "point", "for", "v", "in", "a", "to", "maintain", "sorted", "order", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/internal/bisect/bisect.go#L6-L8
train
c-bata/go-prompt
internal/term/term.go
Restore
func Restore() error { o, err := getOriginalTermios(saveTermiosFD) if err != nil { return err } return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, &o) }
go
func Restore() error { o, err := getOriginalTermios(saveTermiosFD) if err != nil { return err } return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, &o) }
[ "func", "Restore", "(", ")", "error", "{", "o", ",", "err", ":=", "getOriginalTermios", "(", "saveTermiosFD", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "termios", ".", "Tcsetattr", "(", "uintptr", "(", "saveT...
// Restore terminal's mode.
[ "Restore", "terminal", "s", "mode", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/internal/term/term.go#L28-L34
train
c-bata/go-prompt
output_vt100.go
WriteRaw
func (w *VT100Writer) WriteRaw(data []byte) { w.buffer = append(w.buffer, data...) return }
go
func (w *VT100Writer) WriteRaw(data []byte) { w.buffer = append(w.buffer, data...) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "WriteRaw", "(", "data", "[", "]", "byte", ")", "{", "w", ".", "buffer", "=", "append", "(", "w", ".", "buffer", ",", "data", "...", ")", "\n", "return", "\n", "}" ]
// WriteRaw to write raw byte array
[ "WriteRaw", "to", "write", "raw", "byte", "array" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L14-L17
train
c-bata/go-prompt
output_vt100.go
Write
func (w *VT100Writer) Write(data []byte) { w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1)) return }
go
func (w *VT100Writer) Write(data []byte) { w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1)) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "Write", "(", "data", "[", "]", "byte", ")", "{", "w", ".", "WriteRaw", "(", "bytes", ".", "Replace", "(", "data", ",", "[", "]", "byte", "{", "0x1b", "}", ",", "[", "]", "byte", "{", "'?'", "}", ","...
// Write to write safety byte array by removing control sequences.
[ "Write", "to", "write", "safety", "byte", "array", "by", "removing", "control", "sequences", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L20-L23
train
c-bata/go-prompt
output_vt100.go
CursorGoTo
func (w *VT100Writer) CursorGoTo(row, col int) { if row == 0 && col == 0 { // If no row/column parameters are provided (ie. <ESC>[H), the cursor will move to the home position. w.WriteRaw([]byte{0x1b, '[', 'H'}) return } r := strconv.Itoa(row) c := strconv.Itoa(col) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(r)) w.WriteRaw([]byte{';'}) w.WriteRaw([]byte(c)) w.WriteRaw([]byte{'H'}) return }
go
func (w *VT100Writer) CursorGoTo(row, col int) { if row == 0 && col == 0 { // If no row/column parameters are provided (ie. <ESC>[H), the cursor will move to the home position. w.WriteRaw([]byte{0x1b, '[', 'H'}) return } r := strconv.Itoa(row) c := strconv.Itoa(col) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(r)) w.WriteRaw([]byte{';'}) w.WriteRaw([]byte(c)) w.WriteRaw([]byte{'H'}) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "CursorGoTo", "(", "row", ",", "col", "int", ")", "{", "if", "row", "==", "0", "&&", "col", "==", "0", "{", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", ",", "'H'", "}", ")",...
// CursorGoTo sets the cursor position where subsequent text will begin.
[ "CursorGoTo", "sets", "the", "cursor", "position", "where", "subsequent", "text", "will", "begin", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L89-L103
train
c-bata/go-prompt
output_vt100.go
CursorUp
func (w *VT100Writer) CursorUp(n int) { if n == 0 { return } else if n < 0 { w.CursorDown(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'A'}) return }
go
func (w *VT100Writer) CursorUp(n int) { if n == 0 { return } else if n < 0 { w.CursorDown(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'A'}) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "CursorUp", "(", "n", "int", ")", "{", "if", "n", "==", "0", "{", "return", "\n", "}", "else", "if", "n", "<", "0", "{", "w", ".", "CursorDown", "(", "-", "n", ")", "\n", "return", "\n", "}", "\n", ...
// CursorUp moves the cursor up by 'n' rows; the default count is 1.
[ "CursorUp", "moves", "the", "cursor", "up", "by", "n", "rows", ";", "the", "default", "count", "is", "1", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L106-L118
train
c-bata/go-prompt
output_vt100.go
CursorForward
func (w *VT100Writer) CursorForward(n int) { if n == 0 { return } else if n < 0 { w.CursorBackward(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'C'}) return }
go
func (w *VT100Writer) CursorForward(n int) { if n == 0 { return } else if n < 0 { w.CursorBackward(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'C'}) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "CursorForward", "(", "n", "int", ")", "{", "if", "n", "==", "0", "{", "return", "\n", "}", "else", "if", "n", "<", "0", "{", "w", ".", "CursorBackward", "(", "-", "n", ")", "\n", "return", "\n", "}", ...
// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
[ "CursorForward", "moves", "the", "cursor", "forward", "by", "n", "columns", ";", "the", "default", "count", "is", "1", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L136-L148
train
c-bata/go-prompt
output_vt100.go
SetDisplayAttributes
func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) { w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer defer w.WriteRaw([]byte{'m'}) // final character var separator byte = ';' for i := range attrs { p, ok := displayAttributeParameters[attrs[i]] if !ok { continue } w.WriteRaw(p) w.WriteRaw([]byte{separator}) } f, ok := foregroundANSIColors[fg] if !ok { f = foregroundANSIColors[DefaultColor] } w.WriteRaw(f) w.WriteRaw([]byte{separator}) b, ok := backgroundANSIColors[bg] if !ok { b = backgroundANSIColors[DefaultColor] } w.WriteRaw(b) return }
go
func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) { w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer defer w.WriteRaw([]byte{'m'}) // final character var separator byte = ';' for i := range attrs { p, ok := displayAttributeParameters[attrs[i]] if !ok { continue } w.WriteRaw(p) w.WriteRaw([]byte{separator}) } f, ok := foregroundANSIColors[fg] if !ok { f = foregroundANSIColors[DefaultColor] } w.WriteRaw(f) w.WriteRaw([]byte{separator}) b, ok := backgroundANSIColors[bg] if !ok { b = backgroundANSIColors[DefaultColor] } w.WriteRaw(b) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "SetDisplayAttributes", "(", "fg", ",", "bg", "Color", ",", "attrs", "...", "DisplayAttribute", ")", "{", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", "}", ")", "\n", "defer", "w", ...
// SetDisplayAttributes to set VT100 display attributes.
[ "SetDisplayAttributes", "to", "set", "VT100", "display", "attributes", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L247-L273
train
c-bata/go-prompt
option.go
OptionParser
func OptionParser(x ConsoleParser) Option { return func(p *Prompt) error { p.in = x return nil } }
go
func OptionParser(x ConsoleParser) Option { return func(p *Prompt) error { p.in = x return nil } }
[ "func", "OptionParser", "(", "x", "ConsoleParser", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "in", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
[ "OptionParser", "to", "set", "a", "custom", "ConsoleParser", "object", ".", "An", "argument", "should", "implement", "ConsoleParser", "interface", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L8-L13
train
c-bata/go-prompt
option.go
OptionWriter
func OptionWriter(x ConsoleWriter) Option { return func(p *Prompt) error { registerConsoleWriter(x) p.renderer.out = x return nil } }
go
func OptionWriter(x ConsoleWriter) Option { return func(p *Prompt) error { registerConsoleWriter(x) p.renderer.out = x return nil } }
[ "func", "OptionWriter", "(", "x", "ConsoleWriter", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "registerConsoleWriter", "(", "x", ")", "\n", "p", ".", "renderer", ".", "out", "=", "x", "\n", "return", "nil", "\n", ...
// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
[ "OptionWriter", "to", "set", "a", "custom", "ConsoleWriter", "object", ".", "An", "argument", "should", "implement", "ConsoleWriter", "interface", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L16-L22
train
c-bata/go-prompt
option.go
OptionTitle
func OptionTitle(x string) Option { return func(p *Prompt) error { p.renderer.title = x return nil } }
go
func OptionTitle(x string) Option { return func(p *Prompt) error { p.renderer.title = x return nil } }
[ "func", "OptionTitle", "(", "x", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "title", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionTitle to set title displayed at the header bar of terminal.
[ "OptionTitle", "to", "set", "title", "displayed", "at", "the", "header", "bar", "of", "terminal", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L25-L30
train
c-bata/go-prompt
option.go
OptionPrefix
func OptionPrefix(x string) Option { return func(p *Prompt) error { p.renderer.prefix = x return nil } }
go
func OptionPrefix(x string) Option { return func(p *Prompt) error { p.renderer.prefix = x return nil } }
[ "func", "OptionPrefix", "(", "x", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "prefix", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPrefix to set prefix string.
[ "OptionPrefix", "to", "set", "prefix", "string", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L33-L38
train
c-bata/go-prompt
option.go
OptionCompletionWordSeparator
func OptionCompletionWordSeparator(x string) Option { return func(p *Prompt) error { p.completion.wordSeparator = x return nil } }
go
func OptionCompletionWordSeparator(x string) Option { return func(p *Prompt) error { p.completion.wordSeparator = x return nil } }
[ "func", "OptionCompletionWordSeparator", "(", "x", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "completion", ".", "wordSeparator", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
[ "OptionCompletionWordSeparator", "to", "set", "word", "separators", ".", "Enable", "only", "if", "empty", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L41-L46
train
c-bata/go-prompt
option.go
OptionLivePrefix
func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option { return func(p *Prompt) error { p.renderer.livePrefixCallback = f return nil } }
go
func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option { return func(p *Prompt) error { p.renderer.livePrefixCallback = f return nil } }
[ "func", "OptionLivePrefix", "(", "f", "func", "(", ")", "(", "prefix", "string", ",", "useLivePrefix", "bool", ")", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "livePrefixCallback", "=", ...
// OptionLivePrefix to change the prefix dynamically by callback function
[ "OptionLivePrefix", "to", "change", "the", "prefix", "dynamically", "by", "callback", "function" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L49-L54
train
c-bata/go-prompt
option.go
OptionPrefixTextColor
func OptionPrefixTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixTextColor = x return nil } }
go
func OptionPrefixTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixTextColor = x return nil } }
[ "func", "OptionPrefixTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "prefixTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPrefixTextColor change a text color of prefix string
[ "OptionPrefixTextColor", "change", "a", "text", "color", "of", "prefix", "string" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L57-L62
train
c-bata/go-prompt
option.go
OptionPrefixBackgroundColor
func OptionPrefixBackgroundColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixBGColor = x return nil } }
go
func OptionPrefixBackgroundColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixBGColor = x return nil } }
[ "func", "OptionPrefixBackgroundColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "prefixBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPrefixBackgroundColor to change a background color of prefix string
[ "OptionPrefixBackgroundColor", "to", "change", "a", "background", "color", "of", "prefix", "string" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L65-L70
train
c-bata/go-prompt
option.go
OptionInputTextColor
func OptionInputTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputTextColor = x return nil } }
go
func OptionInputTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputTextColor = x return nil } }
[ "func", "OptionInputTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "inputTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionInputTextColor to change a color of text which is input by user
[ "OptionInputTextColor", "to", "change", "a", "color", "of", "text", "which", "is", "input", "by", "user" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L73-L78
train
c-bata/go-prompt
option.go
OptionInputBGColor
func OptionInputBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputBGColor = x return nil } }
go
func OptionInputBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputBGColor = x return nil } }
[ "func", "OptionInputBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "inputBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionInputBGColor to change a color of background which is input by user
[ "OptionInputBGColor", "to", "change", "a", "color", "of", "background", "which", "is", "input", "by", "user" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L81-L86
train
c-bata/go-prompt
option.go
OptionPreviewSuggestionTextColor
func OptionPreviewSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionTextColor = x return nil } }
go
func OptionPreviewSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionTextColor = x return nil } }
[ "func", "OptionPreviewSuggestionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "previewSuggestionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ...
// OptionPreviewSuggestionTextColor to change a text color which is completed
[ "OptionPreviewSuggestionTextColor", "to", "change", "a", "text", "color", "which", "is", "completed" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L89-L94
train
c-bata/go-prompt
option.go
OptionPreviewSuggestionBGColor
func OptionPreviewSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionBGColor = x return nil } }
go
func OptionPreviewSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionBGColor = x return nil } }
[ "func", "OptionPreviewSuggestionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "previewSuggestionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPreviewSuggestionBGColor to change a background color which is completed
[ "OptionPreviewSuggestionBGColor", "to", "change", "a", "background", "color", "which", "is", "completed" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L97-L102
train
c-bata/go-prompt
option.go
OptionSuggestionTextColor
func OptionSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionTextColor = x return nil } }
go
func OptionSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionTextColor = x return nil } }
[ "func", "OptionSuggestionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "suggestionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSuggestionTextColor to change a text color in drop down suggestions.
[ "OptionSuggestionTextColor", "to", "change", "a", "text", "color", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L105-L110
train
c-bata/go-prompt
option.go
OptionSuggestionBGColor
func OptionSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionBGColor = x return nil } }
go
func OptionSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionBGColor = x return nil } }
[ "func", "OptionSuggestionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "suggestionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSuggestionBGColor change a background color in drop down suggestions.
[ "OptionSuggestionBGColor", "change", "a", "background", "color", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L113-L118
train
c-bata/go-prompt
option.go
OptionSelectedSuggestionTextColor
func OptionSelectedSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionTextColor = x return nil } }
go
func OptionSelectedSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionTextColor = x return nil } }
[ "func", "OptionSelectedSuggestionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedSuggestionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}...
// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
[ "OptionSelectedSuggestionTextColor", "to", "change", "a", "text", "color", "for", "completed", "text", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L121-L126
train
c-bata/go-prompt
option.go
OptionSelectedSuggestionBGColor
func OptionSelectedSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionBGColor = x return nil } }
go
func OptionSelectedSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionBGColor = x return nil } }
[ "func", "OptionSelectedSuggestionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedSuggestionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
[ "OptionSelectedSuggestionBGColor", "to", "change", "a", "background", "color", "for", "completed", "text", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L129-L134
train
c-bata/go-prompt
option.go
OptionDescriptionTextColor
func OptionDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionTextColor = x return nil } }
go
func OptionDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionTextColor = x return nil } }
[ "func", "OptionDescriptionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "descriptionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
[ "OptionDescriptionTextColor", "to", "change", "a", "background", "color", "of", "description", "text", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L137-L142
train
c-bata/go-prompt
option.go
OptionDescriptionBGColor
func OptionDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionBGColor = x return nil } }
go
func OptionDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionBGColor = x return nil } }
[ "func", "OptionDescriptionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "descriptionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
[ "OptionDescriptionBGColor", "to", "change", "a", "background", "color", "of", "description", "text", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L145-L150
train
c-bata/go-prompt
option.go
OptionSelectedDescriptionTextColor
func OptionSelectedDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionTextColor = x return nil } }
go
func OptionSelectedDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionTextColor = x return nil } }
[ "func", "OptionSelectedDescriptionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedDescriptionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", ...
// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
[ "OptionSelectedDescriptionTextColor", "to", "change", "a", "text", "color", "of", "description", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L153-L158
train
c-bata/go-prompt
option.go
OptionSelectedDescriptionBGColor
func OptionSelectedDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionBGColor = x return nil } }
go
func OptionSelectedDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionBGColor = x return nil } }
[ "func", "OptionSelectedDescriptionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedDescriptionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ...
// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
[ "OptionSelectedDescriptionBGColor", "to", "change", "a", "background", "color", "of", "description", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L161-L166
train
c-bata/go-prompt
option.go
OptionScrollbarThumbColor
func OptionScrollbarThumbColor(x Color) Option { return func(p *Prompt) error { p.renderer.scrollbarThumbColor = x return nil } }
go
func OptionScrollbarThumbColor(x Color) Option { return func(p *Prompt) error { p.renderer.scrollbarThumbColor = x return nil } }
[ "func", "OptionScrollbarThumbColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "scrollbarThumbColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionScrollbarThumbColor to change a thumb color on scrollbar.
[ "OptionScrollbarThumbColor", "to", "change", "a", "thumb", "color", "on", "scrollbar", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L169-L174
train