repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
bitfinexcom/bitfinex-api-go
v1/client.go
Auth
func (c *Client) Auth(key string, secret string) *Client { c.APIKey = key c.APISecret = secret return c }
go
func (c *Client) Auth(key string, secret string) *Client { c.APIKey = key c.APISecret = secret return c }
[ "func", "(", "c", "*", "Client", ")", "Auth", "(", "key", "string", ",", "secret", "string", ")", "*", "Client", "{", "c", ".", "APIKey", "=", "key", "\n", "c", ".", "APISecret", "=", "secret", "\n\n", "return", "c", "\n", "}" ]
// Auth sets api key and secret for usage is requests that requires authentication.
[ "Auth", "sets", "api", "key", "and", "secret", "for", "usage", "is", "requests", "that", "requires", "authentication", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/client.go#L152-L157
train
bitfinexcom/bitfinex-api-go
v1/client.go
newResponse
func newResponse(r *http.Response) *Response { body, err := ioutil.ReadAll(r.Body) if err != nil { body = []byte(`Error reading body:` + err.Error()) } return &Response{r, body} }
go
func newResponse(r *http.Response) *Response { body, err := ioutil.ReadAll(r.Body) if err != nil { body = []byte(`Error reading body:` + err.Error()) } return &Response{r, body} }
[ "func", "newResponse", "(", "r", "*", "http", ".", "Response", ")", "*", "Response", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "body", "=", "[", "]", "byte", "(", "...
// newResponse creates new wrapper.
[ "newResponse", "creates", "new", "wrapper", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/client.go#L198-L205
train
bitfinexcom/bitfinex-api-go
v2/rest/client.go
NewClientWithSynchronousURLNonce
func NewClientWithSynchronousURLNonce(sync Synchronous, url string, nonce utils.NonceGenerator) *Client { c := &Client{ Synchronous: sync, nonce: nonce, } c.Orders = OrderService{Synchronous: c, requestFactory: c} c.Book = BookService{Synchronous: c} c.Candles = CandleService{Synchronous: c} c.Trades = TradeService{Synchronous: c, requestFactory: c} c.Tickers = TickerService{Synchronous: c, requestFactory: c} c.Platform = PlatformService{Synchronous: c} c.Positions = PositionService{Synchronous: c, requestFactory: c} c.Wallet = WalletService{Synchronous: c, requestFactory: c} c.Ledgers = LedgerService{Synchronous: c, requestFactory: c} return c }
go
func NewClientWithSynchronousURLNonce(sync Synchronous, url string, nonce utils.NonceGenerator) *Client { c := &Client{ Synchronous: sync, nonce: nonce, } c.Orders = OrderService{Synchronous: c, requestFactory: c} c.Book = BookService{Synchronous: c} c.Candles = CandleService{Synchronous: c} c.Trades = TradeService{Synchronous: c, requestFactory: c} c.Tickers = TickerService{Synchronous: c, requestFactory: c} c.Platform = PlatformService{Synchronous: c} c.Positions = PositionService{Synchronous: c, requestFactory: c} c.Wallet = WalletService{Synchronous: c, requestFactory: c} c.Ledgers = LedgerService{Synchronous: c, requestFactory: c} return c }
[ "func", "NewClientWithSynchronousURLNonce", "(", "sync", "Synchronous", ",", "url", "string", ",", "nonce", "utils", ".", "NonceGenerator", ")", "*", "Client", "{", "c", ":=", "&", "Client", "{", "Synchronous", ":", "sync", ",", "nonce", ":", "nonce", ",", ...
// mock me in tests
[ "mock", "me", "in", "tests" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/rest/client.go#L88-L103
train
bitfinexcom/bitfinex-api-go
v2/websocket/subscriptions.go
Reset
func (s *subscriptions) Reset() []*subscription { subs := s.reset() s.lock.Lock() s.hbActive = false s.subsBySubID = make(map[string]*subscription) s.subsByChanID = make(map[int64]*subscription) s.lock.Unlock() return subs }
go
func (s *subscriptions) Reset() []*subscription { subs := s.reset() s.lock.Lock() s.hbActive = false s.subsBySubID = make(map[string]*subscription) s.subsByChanID = make(map[int64]*subscription) s.lock.Unlock() return subs }
[ "func", "(", "s", "*", "subscriptions", ")", "Reset", "(", ")", "[", "]", "*", "subscription", "{", "subs", ":=", "s", ".", "reset", "(", ")", "\n", "s", ".", "lock", ".", "Lock", "(", ")", "\n", "s", ".", "hbActive", "=", "false", "\n", "s", ...
// Reset clears all subscriptions from the currently managed list, and returns // a slice of the existing subscriptions prior to reset. Returns nil if no subscriptions exist.
[ "Reset", "clears", "all", "subscriptions", "from", "the", "currently", "managed", "list", "and", "returns", "a", "slice", "of", "the", "existing", "subscriptions", "prior", "to", "reset", ".", "Returns", "nil", "if", "no", "subscriptions", "exist", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/subscriptions.go#L200-L208
train
bitfinexcom/bitfinex-api-go
v2/types.go
MarshalJSON
func (o *OrderCancelRequest) MarshalJSON() ([]byte, error) { aux := struct { ID int64 `json:"id,omitempty"` CID int64 `json:"cid,omitempty"` CIDDate string `json:"cid_date,omitempty"` }{ ID: o.ID, CID: o.CID, CIDDate: o.CIDDate, } body := []interface{}{0, "oc", nil, aux} return json.Marshal(&body) }
go
func (o *OrderCancelRequest) MarshalJSON() ([]byte, error) { aux := struct { ID int64 `json:"id,omitempty"` CID int64 `json:"cid,omitempty"` CIDDate string `json:"cid_date,omitempty"` }{ ID: o.ID, CID: o.CID, CIDDate: o.CIDDate, } body := []interface{}{0, "oc", nil, aux} return json.Marshal(&body) }
[ "func", "(", "o", "*", "OrderCancelRequest", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "aux", ":=", "struct", "{", "ID", "int64", "`json:\"id,omitempty\"`", "\n", "CID", "int64", "`json:\"cid,omitempty\"`", "\n", "CIDDate",...
// MarshalJSON converts the order cancel object into the format required by the // bitfinex websocket service.
[ "MarshalJSON", "converts", "the", "order", "cancel", "object", "into", "the", "format", "required", "by", "the", "bitfinex", "websocket", "service", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L271-L284
train
bitfinexcom/bitfinex-api-go
v2/types.go
NewOrderFromRaw
func NewOrderFromRaw(raw []interface{}) (o *Order, err error) { if len(raw) == 12 { o = &Order{ ID: int64(f64ValOrZero(raw[0])), Symbol: sValOrEmpty(raw[1]), Amount: f64ValOrZero(raw[2]), AmountOrig: f64ValOrZero(raw[3]), Type: sValOrEmpty(raw[4]), Status: OrderStatus(sValOrEmpty(raw[5])), Price: f64ValOrZero(raw[6]), PriceAvg: f64ValOrZero(raw[7]), MTSUpdated: i64ValOrZero(raw[8]), // 3 trailing zeroes, what do they map to? } } else if len(raw) < 26 { return o, fmt.Errorf("data slice too short for order: %#v", raw) } else { // TODO: API docs say ID, GID, CID, MTS_CREATE, MTS_UPDATE are int but API returns float o = &Order{ ID: int64(f64ValOrZero(raw[0])), GID: int64(f64ValOrZero(raw[1])), CID: int64(f64ValOrZero(raw[2])), Symbol: sValOrEmpty(raw[3]), MTSCreated: int64(f64ValOrZero(raw[4])), MTSUpdated: int64(f64ValOrZero(raw[5])), Amount: f64ValOrZero(raw[6]), AmountOrig: f64ValOrZero(raw[7]), Type: sValOrEmpty(raw[8]), TypePrev: sValOrEmpty(raw[9]), MTSTif: int64(f64ValOrZero(raw[10])), Flags: i64ValOrZero(raw[12]), Status: OrderStatus(sValOrEmpty(raw[13])), Price: f64ValOrZero(raw[16]), PriceAvg: f64ValOrZero(raw[17]), PriceTrailing: f64ValOrZero(raw[18]), PriceAuxLimit: f64ValOrZero(raw[19]), Notify: bValOrFalse(raw[23]), Hidden: bValOrFalse(raw[24]), PlacedID: i64ValOrZero(raw[25]), } } return }
go
func NewOrderFromRaw(raw []interface{}) (o *Order, err error) { if len(raw) == 12 { o = &Order{ ID: int64(f64ValOrZero(raw[0])), Symbol: sValOrEmpty(raw[1]), Amount: f64ValOrZero(raw[2]), AmountOrig: f64ValOrZero(raw[3]), Type: sValOrEmpty(raw[4]), Status: OrderStatus(sValOrEmpty(raw[5])), Price: f64ValOrZero(raw[6]), PriceAvg: f64ValOrZero(raw[7]), MTSUpdated: i64ValOrZero(raw[8]), // 3 trailing zeroes, what do they map to? } } else if len(raw) < 26 { return o, fmt.Errorf("data slice too short for order: %#v", raw) } else { // TODO: API docs say ID, GID, CID, MTS_CREATE, MTS_UPDATE are int but API returns float o = &Order{ ID: int64(f64ValOrZero(raw[0])), GID: int64(f64ValOrZero(raw[1])), CID: int64(f64ValOrZero(raw[2])), Symbol: sValOrEmpty(raw[3]), MTSCreated: int64(f64ValOrZero(raw[4])), MTSUpdated: int64(f64ValOrZero(raw[5])), Amount: f64ValOrZero(raw[6]), AmountOrig: f64ValOrZero(raw[7]), Type: sValOrEmpty(raw[8]), TypePrev: sValOrEmpty(raw[9]), MTSTif: int64(f64ValOrZero(raw[10])), Flags: i64ValOrZero(raw[12]), Status: OrderStatus(sValOrEmpty(raw[13])), Price: f64ValOrZero(raw[16]), PriceAvg: f64ValOrZero(raw[17]), PriceTrailing: f64ValOrZero(raw[18]), PriceAuxLimit: f64ValOrZero(raw[19]), Notify: bValOrFalse(raw[23]), Hidden: bValOrFalse(raw[24]), PlacedID: i64ValOrZero(raw[25]), } } return }
[ "func", "NewOrderFromRaw", "(", "raw", "[", "]", "interface", "{", "}", ")", "(", "o", "*", "Order", ",", "err", "error", ")", "{", "if", "len", "(", "raw", ")", "==", "12", "{", "o", "=", "&", "Order", "{", "ID", ":", "int64", "(", "f64ValOrZe...
// NewOrderFromRaw takes the raw list of values as returned from the websocket // service and tries to convert it into an Order.
[ "NewOrderFromRaw", "takes", "the", "raw", "list", "of", "values", "as", "returned", "from", "the", "websocket", "service", "and", "tries", "to", "convert", "it", "into", "an", "Order", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L346-L389
train
bitfinexcom/bitfinex-api-go
v2/types.go
NewOrderSnapshotFromRaw
func NewOrderSnapshotFromRaw(raw []interface{}) (s *OrderSnapshot, err error) { if len(raw) == 0 { return } os := make([]*Order, 0) switch raw[0].(type) { case []interface{}: for _, v := range raw { if l, ok := v.([]interface{}); ok { o, err := NewOrderFromRaw(l) if err != nil { return s, err } os = append(os, o) } } default: return s, fmt.Errorf("not an order snapshot") } s = &OrderSnapshot{Snapshot: os} return }
go
func NewOrderSnapshotFromRaw(raw []interface{}) (s *OrderSnapshot, err error) { if len(raw) == 0 { return } os := make([]*Order, 0) switch raw[0].(type) { case []interface{}: for _, v := range raw { if l, ok := v.([]interface{}); ok { o, err := NewOrderFromRaw(l) if err != nil { return s, err } os = append(os, o) } } default: return s, fmt.Errorf("not an order snapshot") } s = &OrderSnapshot{Snapshot: os} return }
[ "func", "NewOrderSnapshotFromRaw", "(", "raw", "[", "]", "interface", "{", "}", ")", "(", "s", "*", "OrderSnapshot", ",", "err", "error", ")", "{", "if", "len", "(", "raw", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "os", ":=", "make", "(", ...
// OrderSnapshotFromRaw takes a raw list of values as returned from the websocket // service and tries to convert it into an OrderSnapshot.
[ "OrderSnapshotFromRaw", "takes", "a", "raw", "list", "of", "values", "as", "returned", "from", "the", "websocket", "service", "and", "tries", "to", "convert", "it", "into", "an", "OrderSnapshot", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L393-L416
train
bitfinexcom/bitfinex-api-go
v2/types.go
NewTradeExecutionUpdateFromRaw
func NewTradeExecutionUpdateFromRaw(raw []interface{}) (o *TradeExecutionUpdate, err error) { if len(raw) == 4 { o = &TradeExecutionUpdate{ ID: i64ValOrZero(raw[0]), MTS: i64ValOrZero(raw[1]), ExecAmount: f64ValOrZero(raw[2]), ExecPrice: f64ValOrZero(raw[3]), } return } if len(raw) == 11 { o = &TradeExecutionUpdate{ ID: i64ValOrZero(raw[0]), Pair: sValOrEmpty(raw[1]), MTS: i64ValOrZero(raw[2]), OrderID: i64ValOrZero(raw[3]), ExecAmount: f64ValOrZero(raw[4]), ExecPrice: f64ValOrZero(raw[5]), OrderType: sValOrEmpty(raw[6]), OrderPrice: f64ValOrZero(raw[7]), Maker: iValOrZero(raw[8]), Fee: f64ValOrZero(raw[9]), FeeCurrency: sValOrEmpty(raw[10]), } return } return o, fmt.Errorf("data slice too short for trade update: %#v", raw) }
go
func NewTradeExecutionUpdateFromRaw(raw []interface{}) (o *TradeExecutionUpdate, err error) { if len(raw) == 4 { o = &TradeExecutionUpdate{ ID: i64ValOrZero(raw[0]), MTS: i64ValOrZero(raw[1]), ExecAmount: f64ValOrZero(raw[2]), ExecPrice: f64ValOrZero(raw[3]), } return } if len(raw) == 11 { o = &TradeExecutionUpdate{ ID: i64ValOrZero(raw[0]), Pair: sValOrEmpty(raw[1]), MTS: i64ValOrZero(raw[2]), OrderID: i64ValOrZero(raw[3]), ExecAmount: f64ValOrZero(raw[4]), ExecPrice: f64ValOrZero(raw[5]), OrderType: sValOrEmpty(raw[6]), OrderPrice: f64ValOrZero(raw[7]), Maker: iValOrZero(raw[8]), Fee: f64ValOrZero(raw[9]), FeeCurrency: sValOrEmpty(raw[10]), } return } return o, fmt.Errorf("data slice too short for trade update: %#v", raw) }
[ "func", "NewTradeExecutionUpdateFromRaw", "(", "raw", "[", "]", "interface", "{", "}", ")", "(", "o", "*", "TradeExecutionUpdate", ",", "err", "error", ")", "{", "if", "len", "(", "raw", ")", "==", "4", "{", "o", "=", "&", "TradeExecutionUpdate", "{", ...
// public trade update just looks like a trade
[ "public", "trade", "update", "just", "looks", "like", "a", "trade" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L586-L613
train
bitfinexcom/bitfinex-api-go
v2/types.go
NewMarginInfoFromRaw
func NewMarginInfoFromRaw(raw []interface{}) (o interface{}, err error) { if len(raw) < 2 { return o, fmt.Errorf("data slice too short for margin info base: %#v", raw) } typ, ok := raw[0].(string) if !ok { return o, fmt.Errorf("expected margin info type in first position for margin info but got %#v", raw) } if len(raw) == 2 && typ == "base" { // This should be ["base", [...]] data, ok := raw[1].([]interface{}) if !ok { return o, fmt.Errorf("expected margin info array in second position for margin info but got %#v", raw) } return NewMarginInfoBaseFromRaw(data) } else if len(raw) == 3 && typ == "sym" { // This should be ["sym", SYMBOL, [...]] symbol, ok := raw[1].(string) if !ok { return o, fmt.Errorf("expected margin info symbol in second position for margin info update but got %#v", raw) } data, ok := raw[2].([]interface{}) if !ok { return o, fmt.Errorf("expected margin info array in third position for margin info update but got %#v", raw) } return NewMarginInfoUpdateFromRaw(symbol, data) } return nil, fmt.Errorf("invalid margin info type in %#v", raw) }
go
func NewMarginInfoFromRaw(raw []interface{}) (o interface{}, err error) { if len(raw) < 2 { return o, fmt.Errorf("data slice too short for margin info base: %#v", raw) } typ, ok := raw[0].(string) if !ok { return o, fmt.Errorf("expected margin info type in first position for margin info but got %#v", raw) } if len(raw) == 2 && typ == "base" { // This should be ["base", [...]] data, ok := raw[1].([]interface{}) if !ok { return o, fmt.Errorf("expected margin info array in second position for margin info but got %#v", raw) } return NewMarginInfoBaseFromRaw(data) } else if len(raw) == 3 && typ == "sym" { // This should be ["sym", SYMBOL, [...]] symbol, ok := raw[1].(string) if !ok { return o, fmt.Errorf("expected margin info symbol in second position for margin info update but got %#v", raw) } data, ok := raw[2].([]interface{}) if !ok { return o, fmt.Errorf("expected margin info array in third position for margin info update but got %#v", raw) } return NewMarginInfoUpdateFromRaw(symbol, data) } return nil, fmt.Errorf("invalid margin info type in %#v", raw) }
[ "func", "NewMarginInfoFromRaw", "(", "raw", "[", "]", "interface", "{", "}", ")", "(", "o", "interface", "{", "}", ",", "err", "error", ")", "{", "if", "len", "(", "raw", ")", "<", "2", "{", "return", "o", ",", "fmt", ".", "Errorf", "(", "\"", ...
// marginInfoFromRaw returns either a MarginInfoBase or MarginInfoUpdate, since // the Margin Info is split up into a base and per symbol parts.
[ "marginInfoFromRaw", "returns", "either", "a", "MarginInfoBase", "or", "MarginInfoUpdate", "since", "the", "Margin", "Info", "is", "split", "up", "into", "a", "base", "and", "per", "symbol", "parts", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L768-L800
train
bitfinexcom/bitfinex-api-go
v2/types.go
NewLedgerFromRaw
func NewLedgerFromRaw(raw []interface{}) (o *Ledger, err error) { if len(raw) == 9 { o = &Ledger{ ID: int64(f64ValOrZero(raw[0])), Currency: sValOrEmpty(raw[1]), Nil1: f64ValOrZero(raw[2]), MTS: i64ValOrZero(raw[3]), Nil2: f64ValOrZero(raw[4]), Amount: f64ValOrZero(raw[5]), Balance: f64ValOrZero(raw[6]), Nil3: f64ValOrZero(raw[7]), Description: sValOrEmpty(raw[8]), // API returns 3 Nil values, what do they map to? // API documentation says ID is type integer but api returns a string } } else {return o, fmt.Errorf("data slice too short for ledger: %#v", raw) } return }
go
func NewLedgerFromRaw(raw []interface{}) (o *Ledger, err error) { if len(raw) == 9 { o = &Ledger{ ID: int64(f64ValOrZero(raw[0])), Currency: sValOrEmpty(raw[1]), Nil1: f64ValOrZero(raw[2]), MTS: i64ValOrZero(raw[3]), Nil2: f64ValOrZero(raw[4]), Amount: f64ValOrZero(raw[5]), Balance: f64ValOrZero(raw[6]), Nil3: f64ValOrZero(raw[7]), Description: sValOrEmpty(raw[8]), // API returns 3 Nil values, what do they map to? // API documentation says ID is type integer but api returns a string } } else {return o, fmt.Errorf("data slice too short for ledger: %#v", raw) } return }
[ "func", "NewLedgerFromRaw", "(", "raw", "[", "]", "interface", "{", "}", ")", "(", "o", "*", "Ledger", ",", "err", "error", ")", "{", "if", "len", "(", "raw", ")", "==", "9", "{", "o", "=", "&", "Ledger", "{", "ID", ":", "int64", "(", "f64ValOr...
// NewLedgerFromRaw takes the raw list of values as returned from the websocket // service and tries to convert it into an Ledger.
[ "NewLedgerFromRaw", "takes", "the", "raw", "list", "of", "values", "as", "returned", "from", "the", "websocket", "service", "and", "tries", "to", "convert", "it", "into", "an", "Ledger", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L1561-L1580
train
bitfinexcom/bitfinex-api-go
v2/types.go
NewLedgerSnapshotFromRaw
func NewLedgerSnapshotFromRaw(raw []interface{}) (s *LedgerSnapshot, err error) { if len(raw) == 0 { return s, fmt.Errorf("data slice too short for ledgers: %#v", raw) } os := make([]*Ledger, 0) switch raw[0].(type) { case []interface{}: for _, v := range raw { if l, ok := v.([]interface{}); ok { o, err := NewLedgerFromRaw(l) if err != nil { return s, err } os = append(os, o) } } default: return s, fmt.Errorf("not an ledger snapshot") } s = &LedgerSnapshot{Snapshot: os} return }
go
func NewLedgerSnapshotFromRaw(raw []interface{}) (s *LedgerSnapshot, err error) { if len(raw) == 0 { return s, fmt.Errorf("data slice too short for ledgers: %#v", raw) } os := make([]*Ledger, 0) switch raw[0].(type) { case []interface{}: for _, v := range raw { if l, ok := v.([]interface{}); ok { o, err := NewLedgerFromRaw(l) if err != nil { return s, err } os = append(os, o) } } default: return s, fmt.Errorf("not an ledger snapshot") } s = &LedgerSnapshot{Snapshot: os} return }
[ "func", "NewLedgerSnapshotFromRaw", "(", "raw", "[", "]", "interface", "{", "}", ")", "(", "s", "*", "LedgerSnapshot", ",", "err", "error", ")", "{", "if", "len", "(", "raw", ")", "==", "0", "{", "return", "s", ",", "fmt", ".", "Errorf", "(", "\"",...
// LedgerSnapshotFromRaw takes a raw list of values as returned from the websocket // service and tries to convert it into an LedgerSnapshot.
[ "LedgerSnapshotFromRaw", "takes", "a", "raw", "list", "of", "values", "as", "returned", "from", "the", "websocket", "service", "and", "tries", "to", "convert", "it", "into", "an", "LedgerSnapshot", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/types.go#L1588-L1610
train
bitfinexcom/bitfinex-api-go
v2/rest/platform_status.go
Status
func (p *PlatformService) Status() (bool, error) { raw, err := p.Request(NewRequestWithMethod("platform/status", "GET")) if err != nil { return false, err } /* // raw is an interface type, but we only care about len & index 0 s := make([]int, len(raw)) for i, v := range raw { s[i] = v.(int) } */ return len(raw) > 0 && raw[0].(float64) == 1, nil }
go
func (p *PlatformService) Status() (bool, error) { raw, err := p.Request(NewRequestWithMethod("platform/status", "GET")) if err != nil { return false, err } /* // raw is an interface type, but we only care about len & index 0 s := make([]int, len(raw)) for i, v := range raw { s[i] = v.(int) } */ return len(raw) > 0 && raw[0].(float64) == 1, nil }
[ "func", "(", "p", "*", "PlatformService", ")", "Status", "(", ")", "(", "bool", ",", "error", ")", "{", "raw", ",", "err", ":=", "p", ".", "Request", "(", "NewRequestWithMethod", "(", "\"", "\"", ",", "\"", "\"", ")", ")", "\n\n", "if", "err", "!...
// Status indicates whether the platform is currently operative or not.
[ "Status", "indicates", "whether", "the", "platform", "is", "currently", "operative", "or", "not", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/rest/platform_status.go#L8-L22
train
bitfinexcom/bitfinex-api-go
v2/rest/positions.go
All
func (s *PositionService) All() (*bitfinex.PositionSnapshot, error) { req, err := s.requestFactory.NewAuthenticatedRequest("positions") if err != nil { return nil, err } raw, err := s.Request(req) if err != nil { return nil, err } os, err := bitfinex.NewPositionSnapshotFromRaw(raw) if err != nil { return nil, err } return os, nil }
go
func (s *PositionService) All() (*bitfinex.PositionSnapshot, error) { req, err := s.requestFactory.NewAuthenticatedRequest("positions") if err != nil { return nil, err } raw, err := s.Request(req) if err != nil { return nil, err } os, err := bitfinex.NewPositionSnapshotFromRaw(raw) if err != nil { return nil, err } return os, nil }
[ "func", "(", "s", "*", "PositionService", ")", "All", "(", ")", "(", "*", "bitfinex", ".", "PositionSnapshot", ",", "error", ")", "{", "req", ",", "err", ":=", "s", ".", "requestFactory", ".", "NewAuthenticatedRequest", "(", "\"", "\"", ")", "\n", "if"...
// All returns all positions for the authenticated account.
[ "All", "returns", "all", "positions", "for", "the", "authenticated", "account", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/rest/positions.go#L14-L31
train
bitfinexcom/bitfinex-api-go
v1/offers.go
New
func (s *OffersService) New(currency string, amount, rate float64, period int64, direction string) (Offer, error) { payload := map[string]interface{}{ "currency": currency, "amount": strconv.FormatFloat(amount, 'f', -1, 32), "rate": strconv.FormatFloat(rate, 'f', -1, 32), "period": strconv.FormatInt(period, 10), "direction": direction, } req, err := s.client.newAuthenticatedRequest("POST", "offers/new", payload) if err != nil { return Offer{}, err } var offer = &Offer{} _, err = s.client.do(req, offer) if err != nil { return Offer{}, err } return *offer, nil }
go
func (s *OffersService) New(currency string, amount, rate float64, period int64, direction string) (Offer, error) { payload := map[string]interface{}{ "currency": currency, "amount": strconv.FormatFloat(amount, 'f', -1, 32), "rate": strconv.FormatFloat(rate, 'f', -1, 32), "period": strconv.FormatInt(period, 10), "direction": direction, } req, err := s.client.newAuthenticatedRequest("POST", "offers/new", payload) if err != nil { return Offer{}, err } var offer = &Offer{} _, err = s.client.do(req, offer) if err != nil { return Offer{}, err } return *offer, nil }
[ "func", "(", "s", "*", "OffersService", ")", "New", "(", "currency", "string", ",", "amount", ",", "rate", "float64", ",", "period", "int64", ",", "direction", "string", ")", "(", "Offer", ",", "error", ")", "{", "payload", ":=", "map", "[", "string", ...
// Create new offer for LEND or LOAN a currency, use LEND or LOAN constants as direction
[ "Create", "new", "offer", "for", "LEND", "or", "LOAN", "a", "currency", "use", "LEND", "or", "LOAN", "constants", "as", "direction" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/offers.go#L30-L55
train
bitfinexcom/bitfinex-api-go
v2/websocket/events.go
handleEvent
func (c *Client) handleEvent(msg []byte) error { event := &eventType{} err := json.Unmarshal(msg, event) if err != nil { return err } //var e interface{} switch event.Event { case "info": i := InfoEvent{} err = json.Unmarshal(msg, &i) if err != nil { return err } if i.Code == 0 && i.Version != 0 { err_open := c.handleOpen() if err_open != nil { return err_open } } c.listener <- &i case "auth": a := AuthEvent{} err = json.Unmarshal(msg, &a) if err != nil { return err } if a.Status != "" && a.Status == "OK" { c.Authentication = SuccessfulAuthentication } else { c.Authentication = RejectedAuthentication } c.handleAuthAck(&a) c.listener <- &a return nil case "subscribed": s := SubscribeEvent{} err = json.Unmarshal(msg, &s) if err != nil { return err } err = c.subscriptions.activate(s.SubID, s.ChanID) if err != nil { return err } c.listener <- &s return nil case "unsubscribed": s := UnsubscribeEvent{} err = json.Unmarshal(msg, &s) if err != nil { return err } err_rem := c.subscriptions.removeByChannelID(s.ChanID) if err_rem != nil { return err_rem } c.listener <- &s case "error": er := ErrorEvent{} err = json.Unmarshal(msg, &er) if err != nil { return err } c.listener <- &er case "conf": ec := ConfEvent{} err = json.Unmarshal(msg, &ec) if err != nil { return err } c.listener <- &ec default: c.log.Warningf("unknown event: %s", msg) } //err = json.Unmarshal(msg, &e) //TODO raw message isn't ever published return err }
go
func (c *Client) handleEvent(msg []byte) error { event := &eventType{} err := json.Unmarshal(msg, event) if err != nil { return err } //var e interface{} switch event.Event { case "info": i := InfoEvent{} err = json.Unmarshal(msg, &i) if err != nil { return err } if i.Code == 0 && i.Version != 0 { err_open := c.handleOpen() if err_open != nil { return err_open } } c.listener <- &i case "auth": a := AuthEvent{} err = json.Unmarshal(msg, &a) if err != nil { return err } if a.Status != "" && a.Status == "OK" { c.Authentication = SuccessfulAuthentication } else { c.Authentication = RejectedAuthentication } c.handleAuthAck(&a) c.listener <- &a return nil case "subscribed": s := SubscribeEvent{} err = json.Unmarshal(msg, &s) if err != nil { return err } err = c.subscriptions.activate(s.SubID, s.ChanID) if err != nil { return err } c.listener <- &s return nil case "unsubscribed": s := UnsubscribeEvent{} err = json.Unmarshal(msg, &s) if err != nil { return err } err_rem := c.subscriptions.removeByChannelID(s.ChanID) if err_rem != nil { return err_rem } c.listener <- &s case "error": er := ErrorEvent{} err = json.Unmarshal(msg, &er) if err != nil { return err } c.listener <- &er case "conf": ec := ConfEvent{} err = json.Unmarshal(msg, &ec) if err != nil { return err } c.listener <- &ec default: c.log.Warningf("unknown event: %s", msg) } //err = json.Unmarshal(msg, &e) //TODO raw message isn't ever published return err }
[ "func", "(", "c", "*", "Client", ")", "handleEvent", "(", "msg", "[", "]", "byte", ")", "error", "{", "event", ":=", "&", "eventType", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "msg", ",", "event", ")", "\n", "if", "err", "!=", ...
// onEvent handles all the event messages and connects SubID and ChannelID.
[ "onEvent", "handles", "all", "the", "event", "messages", "and", "connects", "SubID", "and", "ChannelID", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/events.go#L104-L184
train
bitfinexcom/bitfinex-api-go
v1/wallet.go
Transfer
func (c *WalletService) Transfer(amount float64, currency, from, to string) ([]TransferStatus, error) { payload := map[string]interface{}{ "amount": strconv.FormatFloat(amount, 'f', -1, 32), "currency": currency, "walletfrom": from, "walletto": to, } req, err := c.client.newAuthenticatedRequest("GET", "transfer", payload) if err != nil { return nil, err } status := make([]TransferStatus, 0) _, err = c.client.do(req, &status) return status, err }
go
func (c *WalletService) Transfer(amount float64, currency, from, to string) ([]TransferStatus, error) { payload := map[string]interface{}{ "amount": strconv.FormatFloat(amount, 'f', -1, 32), "currency": currency, "walletfrom": from, "walletto": to, } req, err := c.client.newAuthenticatedRequest("GET", "transfer", payload) if err != nil { return nil, err } status := make([]TransferStatus, 0) _, err = c.client.do(req, &status) return status, err }
[ "func", "(", "c", "*", "WalletService", ")", "Transfer", "(", "amount", "float64", ",", "currency", ",", "from", ",", "to", "string", ")", "(", "[", "]", "TransferStatus", ",", "error", ")", "{", "payload", ":=", "map", "[", "string", "]", "interface",...
// Transfer funds between wallets
[ "Transfer", "funds", "between", "wallets" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/wallet.go#L21-L41
train
bitfinexcom/bitfinex-api-go
v1/wallet.go
WithdrawCrypto
func (c *WalletService) WithdrawCrypto(amount float64, currency, wallet, destinationAddress string) ([]WithdrawStatus, error) { payload := map[string]interface{}{ "amount": strconv.FormatFloat(amount, 'f', -1, 32), "walletselected": wallet, "withdraw_type": currency, "address": destinationAddress, } req, err := c.client.newAuthenticatedRequest("GET", "withdraw", payload) if err != nil { return nil, err } status := make([]WithdrawStatus, 0) _, err = c.client.do(req, &status) return status, err }
go
func (c *WalletService) WithdrawCrypto(amount float64, currency, wallet, destinationAddress string) ([]WithdrawStatus, error) { payload := map[string]interface{}{ "amount": strconv.FormatFloat(amount, 'f', -1, 32), "walletselected": wallet, "withdraw_type": currency, "address": destinationAddress, } req, err := c.client.newAuthenticatedRequest("GET", "withdraw", payload) if err != nil { return nil, err } status := make([]WithdrawStatus, 0) _, err = c.client.do(req, &status) return status, err }
[ "func", "(", "c", "*", "WalletService", ")", "WithdrawCrypto", "(", "amount", "float64", ",", "currency", ",", "wallet", ",", "destinationAddress", "string", ")", "(", "[", "]", "WithdrawStatus", ",", "error", ")", "{", "payload", ":=", "map", "[", "string...
// Withdraw a cryptocurrency to a digital wallet
[ "Withdraw", "a", "cryptocurrency", "to", "a", "digital", "wallet" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/wallet.go#L50-L71
train
bitfinexcom/bitfinex-api-go
v2/rest/ledgers.go
Ledgers
func (s *LedgerService) Ledgers(currency string, start int64, end int64, max int32) (*bitfinex.LedgerSnapshot, error) { if max > 500 { return nil, fmt.Errorf("Max request limit is higher then 500 : %#v", max) } req, err := s.requestFactory.NewAuthenticatedRequestWithData(path.Join("ledgers", currency, "hist"), map[string]interface{}{"start": start, "end": end, "limit": max}) if err != nil { return nil, err } raw, err := s.Request(req) if err != nil { return nil, err } os, err := bitfinex.NewLedgerSnapshotFromRaw(raw) if err != nil { return nil, err } return os, nil }
go
func (s *LedgerService) Ledgers(currency string, start int64, end int64, max int32) (*bitfinex.LedgerSnapshot, error) { if max > 500 { return nil, fmt.Errorf("Max request limit is higher then 500 : %#v", max) } req, err := s.requestFactory.NewAuthenticatedRequestWithData(path.Join("ledgers", currency, "hist"), map[string]interface{}{"start": start, "end": end, "limit": max}) if err != nil { return nil, err } raw, err := s.Request(req) if err != nil { return nil, err } os, err := bitfinex.NewLedgerSnapshotFromRaw(raw) if err != nil { return nil, err } return os, nil }
[ "func", "(", "s", "*", "LedgerService", ")", "Ledgers", "(", "currency", "string", ",", "start", "int64", ",", "end", "int64", ",", "max", "int32", ")", "(", "*", "bitfinex", ".", "LedgerSnapshot", ",", "error", ")", "{", "if", "max", ">", "500", "{"...
// All returns all ledgers for the authenticated account.
[ "All", "returns", "all", "ledgers", "for", "the", "authenticated", "account", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/rest/ledgers.go#L16-L36
train
bitfinexcom/bitfinex-api-go
v1/pairs.go
All
func (p *PairsService) All() ([]string, error) { req, err := p.client.newRequest("GET", "symbols", nil) if err != nil { return nil, err } var v []string _, err = p.client.do(req, &v) if err != nil { return nil, err } return v, nil }
go
func (p *PairsService) All() ([]string, error) { req, err := p.client.newRequest("GET", "symbols", nil) if err != nil { return nil, err } var v []string _, err = p.client.do(req, &v) if err != nil { return nil, err } return v, nil }
[ "func", "(", "p", "*", "PairsService", ")", "All", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "req", ",", "err", ":=", "p", ".", "client", ".", "newRequest", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", "if", "err"...
// Get all Pair names as array of strings
[ "Get", "all", "Pair", "names", "as", "array", "of", "strings" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/pairs.go#L8-L22
train
bitfinexcom/bitfinex-api-go
v1/pairs.go
AllDetailed
func (p *PairsService) AllDetailed() ([]Pair, error) { req, err := p.client.newRequest("GET", "symbols_details", nil) if err != nil { return nil, err } var v []Pair _, err = p.client.do(req, &v) if err != nil { return nil, err } return v, nil }
go
func (p *PairsService) AllDetailed() ([]Pair, error) { req, err := p.client.newRequest("GET", "symbols_details", nil) if err != nil { return nil, err } var v []Pair _, err = p.client.do(req, &v) if err != nil { return nil, err } return v, nil }
[ "func", "(", "p", "*", "PairsService", ")", "AllDetailed", "(", ")", "(", "[", "]", "Pair", ",", "error", ")", "{", "req", ",", "err", ":=", "p", ".", "client", ".", "newRequest", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", "if", ...
// Return a list of detailed pairs
[ "Return", "a", "list", "of", "detailed", "pairs" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/pairs.go#L37-L50
train
bitfinexcom/bitfinex-api-go
v2/websocket/orderbook.go
copySide
func (ob *Orderbook) copySide(side []*bitfinex.BookUpdate) []bitfinex.BookUpdate { ob.lock.RLock() defer ob.lock.RUnlock() var cpy []bitfinex.BookUpdate for i := 0; i < len(side); i++ { cpy = append(cpy, *side[i]) } return cpy }
go
func (ob *Orderbook) copySide(side []*bitfinex.BookUpdate) []bitfinex.BookUpdate { ob.lock.RLock() defer ob.lock.RUnlock() var cpy []bitfinex.BookUpdate for i := 0; i < len(side); i++ { cpy = append(cpy, *side[i]) } return cpy }
[ "func", "(", "ob", "*", "Orderbook", ")", "copySide", "(", "side", "[", "]", "*", "bitfinex", ".", "BookUpdate", ")", "[", "]", "bitfinex", ".", "BookUpdate", "{", "ob", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "ob", ".", "lock", ".", ...
// return a dereferenced copy of an orderbook side. This is so consumers can access // the book but not change the values that are used to generate the crc32 checksum
[ "return", "a", "dereferenced", "copy", "of", "an", "orderbook", "side", ".", "This", "is", "so", "consumers", "can", "access", "the", "book", "but", "not", "change", "the", "values", "that", "are", "used", "to", "generate", "the", "crc32", "checksum" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/orderbook.go#L21-L29
train
bitfinexcom/bitfinex-api-go
v1/credits.go
All
func (c *CreditsService) All() ([]Credit, error) { req, err := c.client.newAuthenticatedRequest("GET", "credits", nil) if err != nil { return nil, err } credits := make([]Credit, 0) _, err = c.client.do(req, &credits) if err != nil { return nil, err } return credits, nil }
go
func (c *CreditsService) All() ([]Credit, error) { req, err := c.client.newAuthenticatedRequest("GET", "credits", nil) if err != nil { return nil, err } credits := make([]Credit, 0) _, err = c.client.do(req, &credits) if err != nil { return nil, err } return credits, nil }
[ "func", "(", "c", "*", "CreditsService", ")", "All", "(", ")", "(", "[", "]", "Credit", ",", "error", ")", "{", "req", ",", "err", ":=", "c", ".", "client", ".", "newAuthenticatedRequest", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", ...
// Returns an array of Credit
[ "Returns", "an", "array", "of", "Credit" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/credits.go#L18-L31
train
bitfinexcom/bitfinex-api-go
v1/positions.go
All
func (b *PositionsService) All() ([]Position, error) { req, err := b.client.newAuthenticatedRequest("POST", "positions", nil) if err != nil { return nil, err } var positions []Position _, err = b.client.do(req, &positions) if err != nil { return nil, err } return positions, nil }
go
func (b *PositionsService) All() ([]Position, error) { req, err := b.client.newAuthenticatedRequest("POST", "positions", nil) if err != nil { return nil, err } var positions []Position _, err = b.client.do(req, &positions) if err != nil { return nil, err } return positions, nil }
[ "func", "(", "b", "*", "PositionsService", ")", "All", "(", ")", "(", "[", "]", "Position", ",", "error", ")", "{", "req", ",", "err", ":=", "b", ".", "client", ".", "newAuthenticatedRequest", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\...
// All - gets all positions
[ "All", "-", "gets", "all", "positions" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/positions.go#L35-L48
train
bitfinexcom/bitfinex-api-go
v1/positions.go
Claim
func (b *PositionsService) Claim(positionId int, amount string) (Position, error) { request := map[string]interface{}{ "position_id": positionId, "amount": amount, } req, err := b.client.newAuthenticatedRequest("POST", "position/claim", request) if err != nil { return Position{}, err } var position = &Position{} _, err = b.client.do(req, position) if err != nil { return Position{}, err } return *position, nil }
go
func (b *PositionsService) Claim(positionId int, amount string) (Position, error) { request := map[string]interface{}{ "position_id": positionId, "amount": amount, } req, err := b.client.newAuthenticatedRequest("POST", "position/claim", request) if err != nil { return Position{}, err } var position = &Position{} _, err = b.client.do(req, position) if err != nil { return Position{}, err } return *position, nil }
[ "func", "(", "b", "*", "PositionsService", ")", "Claim", "(", "positionId", "int", ",", "amount", "string", ")", "(", "Position", ",", "error", ")", "{", "request", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "positi...
// Claim a position
[ "Claim", "a", "position" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/positions.go#L51-L73
train
bitfinexcom/bitfinex-api-go
v2/rest/orders.go
OrderTrades
func (s *OrderService) OrderTrades(symbol string, orderID int64) (*bitfinex.TradeExecutionUpdateSnapshot, error) { if symbol == "" { return nil, fmt.Errorf("symbol cannot be empty") } key := fmt.Sprintf("%s:%d", symbol, orderID) req, err := s.requestFactory.NewAuthenticatedRequest(path.Join("order", key, "trades")) if err != nil { return nil, err } raw, err := s.Request(req) if err != nil { return nil, err } return bitfinex.NewTradeExecutionUpdateSnapshotFromRaw(raw) }
go
func (s *OrderService) OrderTrades(symbol string, orderID int64) (*bitfinex.TradeExecutionUpdateSnapshot, error) { if symbol == "" { return nil, fmt.Errorf("symbol cannot be empty") } key := fmt.Sprintf("%s:%d", symbol, orderID) req, err := s.requestFactory.NewAuthenticatedRequest(path.Join("order", key, "trades")) if err != nil { return nil, err } raw, err := s.Request(req) if err != nil { return nil, err } return bitfinex.NewTradeExecutionUpdateSnapshotFromRaw(raw) }
[ "func", "(", "s", "*", "OrderService", ")", "OrderTrades", "(", "symbol", "string", ",", "orderID", "int64", ")", "(", "*", "bitfinex", ".", "TradeExecutionUpdateSnapshot", ",", "error", ")", "{", "if", "symbol", "==", "\"", "\"", "{", "return", "nil", "...
// OrderTrades returns a set of executed trades related to an order.
[ "OrderTrades", "returns", "a", "set", "of", "executed", "trades", "related", "to", "an", "order", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/rest/orders.go#L79-L93
train
bitfinexcom/bitfinex-api-go
v1/orders.go
CancelAll
func (s *OrderService) CancelAll() error { req, err := s.client.newAuthenticatedRequest("POST", "order/cancel/all", nil) if err != nil { return err } _, err = s.client.do(req, nil) if err != nil { return err } return nil }
go
func (s *OrderService) CancelAll() error { req, err := s.client.newAuthenticatedRequest("POST", "order/cancel/all", nil) if err != nil { return err } _, err = s.client.do(req, nil) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "OrderService", ")", "CancelAll", "(", ")", "error", "{", "req", ",", "err", ":=", "s", ".", "client", ".", "newAuthenticatedRequest", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", ...
// CancelAll active orders for the authenticated account.
[ "CancelAll", "active", "orders", "for", "the", "authenticated", "account", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L63-L75
train
bitfinexcom/bitfinex-api-go
v1/orders.go
Create
func (s *OrderService) Create(symbol string, amount float64, price float64, orderType string) (*Order, error) { var side string if amount < 0 { amount = math.Abs(amount) side = "sell" } else { side = "buy" } payload := map[string]interface{}{ "symbol": symbol, "amount": strconv.FormatFloat(amount, 'f', -1, 32), "price": strconv.FormatFloat(price, 'f', -1, 32), "side": side, "type": orderType, "exchange": "bitfinex", } req, err := s.client.newAuthenticatedRequest("POST", "order/new", payload) if err != nil { return nil, err } order := new(Order) _, err = s.client.do(req, order) if err != nil { return nil, err } return order, nil }
go
func (s *OrderService) Create(symbol string, amount float64, price float64, orderType string) (*Order, error) { var side string if amount < 0 { amount = math.Abs(amount) side = "sell" } else { side = "buy" } payload := map[string]interface{}{ "symbol": symbol, "amount": strconv.FormatFloat(amount, 'f', -1, 32), "price": strconv.FormatFloat(price, 'f', -1, 32), "side": side, "type": orderType, "exchange": "bitfinex", } req, err := s.client.newAuthenticatedRequest("POST", "order/new", payload) if err != nil { return nil, err } order := new(Order) _, err = s.client.do(req, order) if err != nil { return nil, err } return order, nil }
[ "func", "(", "s", "*", "OrderService", ")", "Create", "(", "symbol", "string", ",", "amount", "float64", ",", "price", "float64", ",", "orderType", "string", ")", "(", "*", "Order", ",", "error", ")", "{", "var", "side", "string", "\n", "if", "amount",...
// Create a new order.
[ "Create", "a", "new", "order", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L78-L108
train
bitfinexcom/bitfinex-api-go
v1/orders.go
Cancel
func (s *OrderService) Cancel(orderID int64) error { payload := map[string]interface{}{ "order_id": orderID, } req, err := s.client.newAuthenticatedRequest("POST", "order/cancel", payload) if err != nil { return err } _, err = s.client.do(req, nil) if err != nil { return err } return nil }
go
func (s *OrderService) Cancel(orderID int64) error { payload := map[string]interface{}{ "order_id": orderID, } req, err := s.client.newAuthenticatedRequest("POST", "order/cancel", payload) if err != nil { return err } _, err = s.client.do(req, nil) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "OrderService", ")", "Cancel", "(", "orderID", "int64", ")", "error", "{", "payload", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "orderID", ",", "}", "\n\n", "req", ",", "err", ":=", "s", ...
// Cancel the order with id `orderID`.
[ "Cancel", "the", "order", "with", "id", "orderID", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L111-L127
train
bitfinexcom/bitfinex-api-go
v1/orders.go
CreateMulti
func (s *OrderService) CreateMulti(orders []SubmitOrder) (MultipleOrderResponse, error) { ordersMap := make([]interface{}, 0) for _, order := range orders { var side string if order.Amount < 0 { order.Amount = math.Abs(order.Amount) side = "sell" } else { side = "buy" } ordersMap = append(ordersMap, map[string]interface{}{ "symbol": order.Symbol, "amount": strconv.FormatFloat(order.Amount, 'f', -1, 32), "price": strconv.FormatFloat(order.Price, 'f', -1, 32), "exchange": "bitfinex", "side": side, "type": order.Type, }) } payload := map[string]interface{}{ "orders": ordersMap, } req, err := s.client.newAuthenticatedRequest("POST", "order/new/multi", payload) if err != nil { return MultipleOrderResponse{}, err } response := new(MultipleOrderResponse) _, err = s.client.do(req, response) return *response, err }
go
func (s *OrderService) CreateMulti(orders []SubmitOrder) (MultipleOrderResponse, error) { ordersMap := make([]interface{}, 0) for _, order := range orders { var side string if order.Amount < 0 { order.Amount = math.Abs(order.Amount) side = "sell" } else { side = "buy" } ordersMap = append(ordersMap, map[string]interface{}{ "symbol": order.Symbol, "amount": strconv.FormatFloat(order.Amount, 'f', -1, 32), "price": strconv.FormatFloat(order.Price, 'f', -1, 32), "exchange": "bitfinex", "side": side, "type": order.Type, }) } payload := map[string]interface{}{ "orders": ordersMap, } req, err := s.client.newAuthenticatedRequest("POST", "order/new/multi", payload) if err != nil { return MultipleOrderResponse{}, err } response := new(MultipleOrderResponse) _, err = s.client.do(req, response) return *response, err }
[ "func", "(", "s", "*", "OrderService", ")", "CreateMulti", "(", "orders", "[", "]", "SubmitOrder", ")", "(", "MultipleOrderResponse", ",", "error", ")", "{", "ordersMap", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ")", "\n", "for", ...
// CreateMulti allows batch creation of orders.
[ "CreateMulti", "allows", "batch", "creation", "of", "orders", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L144-L178
train
bitfinexcom/bitfinex-api-go
v1/orders.go
CancelMulti
func (s *OrderService) CancelMulti(orderIDS []int64) (string, error) { payload := map[string]interface{}{ "order_ids": orderIDS, } req, err := s.client.newAuthenticatedRequest("POST", "order/cancel/multi", payload) if err != nil { return "", err } response := make(map[string]string) _, err = s.client.do(req, &response) return response["result"], err }
go
func (s *OrderService) CancelMulti(orderIDS []int64) (string, error) { payload := map[string]interface{}{ "order_ids": orderIDS, } req, err := s.client.newAuthenticatedRequest("POST", "order/cancel/multi", payload) if err != nil { return "", err } response := make(map[string]string) _, err = s.client.do(req, &response) return response["result"], err }
[ "func", "(", "s", "*", "OrderService", ")", "CancelMulti", "(", "orderIDS", "[", "]", "int64", ")", "(", "string", ",", "error", ")", "{", "payload", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "orderIDS", ",", "}"...
// CancelMulti allows batch cancellation of orders.
[ "CancelMulti", "allows", "batch", "cancellation", "of", "orders", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L181-L196
train
bitfinexcom/bitfinex-api-go
v1/orders.go
Replace
func (s *OrderService) Replace(orderID int64, useRemaining bool, newOrder SubmitOrder) (Order, error) { var side string if newOrder.Amount < 0 { newOrder.Amount = math.Abs(newOrder.Amount) side = "sell" } else { side = "buy" } payload := map[string]interface{}{ "order_id": strconv.FormatInt(orderID, 10), "symbol": newOrder.Symbol, "amount": strconv.FormatFloat(newOrder.Amount, 'f', -1, 32), "price": strconv.FormatFloat(newOrder.Price, 'f', -1, 32), "exchange": "bitfinex", "side": side, "type": newOrder.Type, "use_remaining": useRemaining, } req, err := s.client.newAuthenticatedRequest("POST", "order/cancel/replace", payload) if err != nil { return Order{}, err } order := new(Order) _, err = s.client.do(req, order) if err != nil { return *order, err } return *order, nil }
go
func (s *OrderService) Replace(orderID int64, useRemaining bool, newOrder SubmitOrder) (Order, error) { var side string if newOrder.Amount < 0 { newOrder.Amount = math.Abs(newOrder.Amount) side = "sell" } else { side = "buy" } payload := map[string]interface{}{ "order_id": strconv.FormatInt(orderID, 10), "symbol": newOrder.Symbol, "amount": strconv.FormatFloat(newOrder.Amount, 'f', -1, 32), "price": strconv.FormatFloat(newOrder.Price, 'f', -1, 32), "exchange": "bitfinex", "side": side, "type": newOrder.Type, "use_remaining": useRemaining, } req, err := s.client.newAuthenticatedRequest("POST", "order/cancel/replace", payload) if err != nil { return Order{}, err } order := new(Order) _, err = s.client.do(req, order) if err != nil { return *order, err } return *order, nil }
[ "func", "(", "s", "*", "OrderService", ")", "Replace", "(", "orderID", "int64", ",", "useRemaining", "bool", ",", "newOrder", "SubmitOrder", ")", "(", "Order", ",", "error", ")", "{", "var", "side", "string", "\n", "if", "newOrder", ".", "Amount", "<", ...
// Replace an Order
[ "Replace", "an", "Order" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L199-L231
train
bitfinexcom/bitfinex-api-go
v1/orders.go
Status
func (s *OrderService) Status(orderID int64) (Order, error) { payload := map[string]interface{}{ "order_id": orderID, } req, err := s.client.newAuthenticatedRequest("POST", "order/status", payload) if err != nil { return Order{}, err } order := new(Order) _, err = s.client.do(req, order) if err != nil { return *order, err } return *order, nil }
go
func (s *OrderService) Status(orderID int64) (Order, error) { payload := map[string]interface{}{ "order_id": orderID, } req, err := s.client.newAuthenticatedRequest("POST", "order/status", payload) if err != nil { return Order{}, err } order := new(Order) _, err = s.client.do(req, order) if err != nil { return *order, err } return *order, nil }
[ "func", "(", "s", "*", "OrderService", ")", "Status", "(", "orderID", "int64", ")", "(", "Order", ",", "error", ")", "{", "payload", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "orderID", ",", "}", "\n\n", "req", ...
// Status retrieves the given order from the API.
[ "Status", "retrieves", "the", "given", "order", "from", "the", "API", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/orders.go#L234-L253
train
firstrow/tcp_server
tcp_server.go
listen
func (c *Client) listen() { c.Server.onNewClientCallback(c) reader := bufio.NewReader(c.conn) for { message, err := reader.ReadString('\n') if err != nil { c.conn.Close() c.Server.onClientConnectionClosed(c, err) return } c.Server.onNewMessage(c, message) } }
go
func (c *Client) listen() { c.Server.onNewClientCallback(c) reader := bufio.NewReader(c.conn) for { message, err := reader.ReadString('\n') if err != nil { c.conn.Close() c.Server.onClientConnectionClosed(c, err) return } c.Server.onNewMessage(c, message) } }
[ "func", "(", "c", "*", "Client", ")", "listen", "(", ")", "{", "c", ".", "Server", ".", "onNewClientCallback", "(", "c", ")", "\n", "reader", ":=", "bufio", ".", "NewReader", "(", "c", ".", "conn", ")", "\n", "for", "{", "message", ",", "err", ":...
// Read client data from channel
[ "Read", "client", "data", "from", "channel" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L26-L38
train
firstrow/tcp_server
tcp_server.go
Send
func (c *Client) Send(message string) error { _, err := c.conn.Write([]byte(message)) return err }
go
func (c *Client) Send(message string) error { _, err := c.conn.Write([]byte(message)) return err }
[ "func", "(", "c", "*", "Client", ")", "Send", "(", "message", "string", ")", "error", "{", "_", ",", "err", ":=", "c", ".", "conn", ".", "Write", "(", "[", "]", "byte", "(", "message", ")", ")", "\n", "return", "err", "\n", "}" ]
// Send text message to client
[ "Send", "text", "message", "to", "client" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L41-L44
train
firstrow/tcp_server
tcp_server.go
SendBytes
func (c *Client) SendBytes(b []byte) error { _, err := c.conn.Write(b) return err }
go
func (c *Client) SendBytes(b []byte) error { _, err := c.conn.Write(b) return err }
[ "func", "(", "c", "*", "Client", ")", "SendBytes", "(", "b", "[", "]", "byte", ")", "error", "{", "_", ",", "err", ":=", "c", ".", "conn", ".", "Write", "(", "b", ")", "\n", "return", "err", "\n", "}" ]
// Send bytes to client
[ "Send", "bytes", "to", "client" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L47-L50
train
firstrow/tcp_server
tcp_server.go
OnClientConnectionClosed
func (s *server) OnClientConnectionClosed(callback func(c *Client, err error)) { s.onClientConnectionClosed = callback }
go
func (s *server) OnClientConnectionClosed(callback func(c *Client, err error)) { s.onClientConnectionClosed = callback }
[ "func", "(", "s", "*", "server", ")", "OnClientConnectionClosed", "(", "callback", "func", "(", "c", "*", "Client", ",", "err", "error", ")", ")", "{", "s", ".", "onClientConnectionClosed", "=", "callback", "\n", "}" ]
// Called right after connection closed
[ "Called", "right", "after", "connection", "closed" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L66-L68
train
firstrow/tcp_server
tcp_server.go
OnNewMessage
func (s *server) OnNewMessage(callback func(c *Client, message string)) { s.onNewMessage = callback }
go
func (s *server) OnNewMessage(callback func(c *Client, message string)) { s.onNewMessage = callback }
[ "func", "(", "s", "*", "server", ")", "OnNewMessage", "(", "callback", "func", "(", "c", "*", "Client", ",", "message", "string", ")", ")", "{", "s", ".", "onNewMessage", "=", "callback", "\n", "}" ]
// Called when Client receives new message
[ "Called", "when", "Client", "receives", "new", "message" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L71-L73
train
firstrow/tcp_server
tcp_server.go
Listen
func (s *server) Listen() { var listener net.Listener var err error if s.config == nil { listener, err = net.Listen("tcp", s.address) } else { listener, err = tls.Listen("tcp", s.address, s.config) } if err != nil { log.Fatal("Error starting TCP server.") } defer listener.Close() for { conn, _ := listener.Accept() client := &Client{ conn: conn, Server: s, } go client.listen() } }
go
func (s *server) Listen() { var listener net.Listener var err error if s.config == nil { listener, err = net.Listen("tcp", s.address) } else { listener, err = tls.Listen("tcp", s.address, s.config) } if err != nil { log.Fatal("Error starting TCP server.") } defer listener.Close() for { conn, _ := listener.Accept() client := &Client{ conn: conn, Server: s, } go client.listen() } }
[ "func", "(", "s", "*", "server", ")", "Listen", "(", ")", "{", "var", "listener", "net", ".", "Listener", "\n", "var", "err", "error", "\n", "if", "s", ".", "config", "==", "nil", "{", "listener", ",", "err", "=", "net", ".", "Listen", "(", "\"",...
// Listen starts network server
[ "Listen", "starts", "network", "server" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L76-L97
train
firstrow/tcp_server
tcp_server.go
New
func New(address string) *server { log.Println("Creating server with address", address) server := &server{ address: address, config: nil, } server.OnNewClient(func(c *Client) {}) server.OnNewMessage(func(c *Client, message string) {}) server.OnClientConnectionClosed(func(c *Client, err error) {}) return server }
go
func New(address string) *server { log.Println("Creating server with address", address) server := &server{ address: address, config: nil, } server.OnNewClient(func(c *Client) {}) server.OnNewMessage(func(c *Client, message string) {}) server.OnClientConnectionClosed(func(c *Client, err error) {}) return server }
[ "func", "New", "(", "address", "string", ")", "*", "server", "{", "log", ".", "Println", "(", "\"", "\"", ",", "address", ")", "\n", "server", ":=", "&", "server", "{", "address", ":", "address", ",", "config", ":", "nil", ",", "}", "\n\n", "server...
// Creates new tcp server instance
[ "Creates", "new", "tcp", "server", "instance" ]
b7a05ff2879d47e69dadf22f9149a86544d7efeb
https://github.com/firstrow/tcp_server/blob/b7a05ff2879d47e69dadf22f9149a86544d7efeb/tcp_server.go#L100-L112
train
rethinkdb/rethinkdb-go
cursor.go
Profile
func (c *Cursor) Profile() interface{} { if c == nil { return nil } c.mu.RLock() defer c.mu.RUnlock() return c.profile }
go
func (c *Cursor) Profile() interface{} { if c == nil { return nil } c.mu.RLock() defer c.mu.RUnlock() return c.profile }
[ "func", "(", "c", "*", "Cursor", ")", "Profile", "(", ")", "interface", "{", "}", "{", "if", "c", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "("...
// Profile returns the information returned from the query profiler.
[ "Profile", "returns", "the", "information", "returned", "from", "the", "query", "profiler", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L86-L95
train
rethinkdb/rethinkdb-go
cursor.go
Close
func (c *Cursor) Close() error { if c == nil { return errNilCursor } c.mu.Lock() defer c.mu.Unlock() var err error // If cursor is already closed return immediately closed := c.closed if closed { return nil } // Get connection and check its valid, don't need to lock as this is only // set when the cursor is created conn := c.conn if conn == nil { return nil } if conn.Conn == nil { return nil } // Stop any unfinished queries if !c.finished { _, _, err = conn.Query(c.ctx, newStopQuery(c.token)) } if c.releaseConn != nil { if err := c.releaseConn(); err != nil { return err } } if span := opentracing.SpanFromContext(c.ctx); span != nil { span.Finish() } c.closed = true c.conn = nil c.buffer = nil c.responses = nil return err }
go
func (c *Cursor) Close() error { if c == nil { return errNilCursor } c.mu.Lock() defer c.mu.Unlock() var err error // If cursor is already closed return immediately closed := c.closed if closed { return nil } // Get connection and check its valid, don't need to lock as this is only // set when the cursor is created conn := c.conn if conn == nil { return nil } if conn.Conn == nil { return nil } // Stop any unfinished queries if !c.finished { _, _, err = conn.Query(c.ctx, newStopQuery(c.token)) } if c.releaseConn != nil { if err := c.releaseConn(); err != nil { return err } } if span := opentracing.SpanFromContext(c.ctx); span != nil { span.Finish() } c.closed = true c.conn = nil c.buffer = nil c.responses = nil return err }
[ "func", "(", "c", "*", "Cursor", ")", "Close", "(", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "errNilCursor", "\n", "}", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\...
// Close closes the cursor, preventing further enumeration. If the end is // encountered, the cursor is closed automatically. Close is idempotent.
[ "Close", "closes", "the", "cursor", "preventing", "further", "enumeration", ".", "If", "the", "end", "is", "encountered", "the", "cursor", "is", "closed", "automatically", ".", "Close", "is", "idempotent", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L124-L171
train
rethinkdb/rethinkdb-go
cursor.go
Next
func (c *Cursor) Next(dest interface{}) bool { if c == nil { return false } c.mu.Lock() if c.closed { c.mu.Unlock() return false } hasMore, err := c.nextLocked(dest, true) if c.handleErrorLocked(err) != nil { c.mu.Unlock() c.Close() return false } c.mu.Unlock() if !hasMore { c.Close() } return hasMore }
go
func (c *Cursor) Next(dest interface{}) bool { if c == nil { return false } c.mu.Lock() if c.closed { c.mu.Unlock() return false } hasMore, err := c.nextLocked(dest, true) if c.handleErrorLocked(err) != nil { c.mu.Unlock() c.Close() return false } c.mu.Unlock() if !hasMore { c.Close() } return hasMore }
[ "func", "(", "c", "*", "Cursor", ")", "Next", "(", "dest", "interface", "{", "}", ")", "bool", "{", "if", "c", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "c", ".", "closed", "{",...
// Next retrieves the next document from the result set, blocking if necessary. // This method will also automatically retrieve another batch of documents from // the server when the current one is exhausted, or before that in background // if possible. // // Next returns true if a document was successfully unmarshalled onto result, // and false at the end of the result set or if an error happened. // When Next returns false, the Err method should be called to verify if // there was an error during iteration. // // Also note that you are able to reuse the same variable multiple times as // `Next` zeroes the value before scanning in the result.
[ "Next", "retrieves", "the", "next", "document", "from", "the", "result", "set", "blocking", "if", "necessary", ".", "This", "method", "will", "also", "automatically", "retrieve", "another", "batch", "of", "documents", "from", "the", "server", "when", "the", "c...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L185-L209
train
rethinkdb/rethinkdb-go
cursor.go
Skip
func (c *Cursor) Skip() { if c == nil { return } c.mu.Lock() defer c.mu.Unlock() c.pendingSkips++ }
go
func (c *Cursor) Skip() { if c == nil { return } c.mu.Lock() defer c.mu.Unlock() c.pendingSkips++ }
[ "func", "(", "c", "*", "Cursor", ")", "Skip", "(", ")", "{", "if", "c", "==", "nil", "{", "return", "\n", "}", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", ".", "pendingSk...
// Skip progresses the cursor by one record. It is useful after a successful // Peek to avoid duplicate decoding work.
[ "Skip", "progresses", "the", "cursor", "by", "one", "record", ".", "It", "is", "useful", "after", "a", "successful", "Peek", "to", "avoid", "duplicate", "decoding", "work", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L288-L296
train
rethinkdb/rethinkdb-go
cursor.go
All
func (c *Cursor) All(result interface{}) error { if c == nil { return errNilCursor } resultv := reflect.ValueOf(result) if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice { panic("result argument must be a slice address") } slicev := resultv.Elem() slicev = slicev.Slice(0, slicev.Cap()) elemt := slicev.Type().Elem() i := 0 for { if slicev.Len() == i { elemp := reflect.New(elemt) if !c.Next(elemp.Interface()) { break } slicev = reflect.Append(slicev, elemp.Elem()) slicev = slicev.Slice(0, slicev.Cap()) } else { if !c.Next(slicev.Index(i).Addr().Interface()) { break } } i++ } resultv.Elem().Set(slicev.Slice(0, i)) if err := c.Err(); err != nil { c.Close() return err } if err := c.Close(); err != nil { return err } return nil }
go
func (c *Cursor) All(result interface{}) error { if c == nil { return errNilCursor } resultv := reflect.ValueOf(result) if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice { panic("result argument must be a slice address") } slicev := resultv.Elem() slicev = slicev.Slice(0, slicev.Cap()) elemt := slicev.Type().Elem() i := 0 for { if slicev.Len() == i { elemp := reflect.New(elemt) if !c.Next(elemp.Interface()) { break } slicev = reflect.Append(slicev, elemp.Elem()) slicev = slicev.Slice(0, slicev.Cap()) } else { if !c.Next(slicev.Index(i).Addr().Interface()) { break } } i++ } resultv.Elem().Set(slicev.Slice(0, i)) if err := c.Err(); err != nil { c.Close() return err } if err := c.Close(); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Cursor", ")", "All", "(", "result", "interface", "{", "}", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "errNilCursor", "\n", "}", "\n\n", "resultv", ":=", "reflect", ".", "ValueOf", "(", "result", ")", "\n", "i...
// All retrieves all documents from the result set into the provided slice // and closes the cursor. // // The result argument must necessarily be the address for a slice. The slice // may be nil or previously allocated. // // Also note that you are able to reuse the same variable multiple times as // `All` zeroes the value before scanning in the result. It also attempts // to reuse the existing slice without allocating any more space by either // resizing or returning a selection of the slice if necessary.
[ "All", "retrieves", "all", "documents", "from", "the", "result", "set", "into", "the", "provided", "slice", "and", "closes", "the", "cursor", ".", "The", "result", "argument", "must", "necessarily", "be", "the", "address", "for", "a", "slice", ".", "The", ...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L359-L399
train
rethinkdb/rethinkdb-go
cursor.go
One
func (c *Cursor) One(result interface{}) error { if c == nil { return errNilCursor } if c.IsNil() { c.Close() return ErrEmptyResult } hasResult := c.Next(result) if err := c.Err(); err != nil { c.Close() return err } if err := c.Close(); err != nil { return err } if !hasResult { return ErrEmptyResult } return nil }
go
func (c *Cursor) One(result interface{}) error { if c == nil { return errNilCursor } if c.IsNil() { c.Close() return ErrEmptyResult } hasResult := c.Next(result) if err := c.Err(); err != nil { c.Close() return err } if err := c.Close(); err != nil { return err } if !hasResult { return ErrEmptyResult } return nil }
[ "func", "(", "c", "*", "Cursor", ")", "One", "(", "result", "interface", "{", "}", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "errNilCursor", "\n", "}", "\n\n", "if", "c", ".", "IsNil", "(", ")", "{", "c", ".", "Close", "(", ")",...
// One retrieves a single document from the result set into the provided // slice and closes the cursor. // // Also note that you are able to reuse the same variable multiple times as // `One` zeroes the value before scanning in the result.
[ "One", "retrieves", "a", "single", "document", "from", "the", "result", "set", "into", "the", "provided", "slice", "and", "closes", "the", "cursor", ".", "Also", "note", "that", "you", "are", "able", "to", "reuse", "the", "same", "variable", "multiple", "t...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L406-L432
train
rethinkdb/rethinkdb-go
cursor.go
IsNil
func (c *Cursor) IsNil() bool { if c == nil { return true } c.mu.RLock() defer c.mu.RUnlock() if len(c.buffer) > 0 { return c.buffer[0] == nil } if len(c.responses) > 0 { response := c.responses[0] if response == nil { return true } if string(response) == "null" { return true } return false } return true }
go
func (c *Cursor) IsNil() bool { if c == nil { return true } c.mu.RLock() defer c.mu.RUnlock() if len(c.buffer) > 0 { return c.buffer[0] == nil } if len(c.responses) > 0 { response := c.responses[0] if response == nil { return true } if string(response) == "null" { return true } return false } return true }
[ "func", "(", "c", "*", "Cursor", ")", "IsNil", "(", ")", "bool", "{", "if", "c", "==", "nil", "{", "return", "true", "\n", "}", "\n\n", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", ...
// IsNil tests if the current row is nil.
[ "IsNil", "tests", "if", "the", "current", "row", "is", "nil", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L507-L533
train
rethinkdb/rethinkdb-go
cursor.go
fetchMore
func (c *Cursor) fetchMore() error { var err error if !c.fetching { c.fetching = true if c.closed { return errCursorClosed } q := Query{ Type: p.Query_CONTINUE, Token: c.token, } c.mu.Unlock() _, _, err = c.conn.Query(c.ctx, q) c.mu.Lock() } return err }
go
func (c *Cursor) fetchMore() error { var err error if !c.fetching { c.fetching = true if c.closed { return errCursorClosed } q := Query{ Type: p.Query_CONTINUE, Token: c.token, } c.mu.Unlock() _, _, err = c.conn.Query(c.ctx, q) c.mu.Lock() } return err }
[ "func", "(", "c", "*", "Cursor", ")", "fetchMore", "(", ")", "error", "{", "var", "err", "error", "\n\n", "if", "!", "c", ".", "fetching", "{", "c", ".", "fetching", "=", "true", "\n\n", "if", "c", ".", "closed", "{", "return", "errCursorClosed", "...
// fetchMore fetches more rows from the database. // // If wait is true then it will wait for the database to reply otherwise it // will return after sending the continue query.
[ "fetchMore", "fetches", "more", "rows", "from", "the", "database", ".", "If", "wait", "is", "true", "then", "it", "will", "wait", "for", "the", "database", "to", "reply", "otherwise", "it", "will", "return", "after", "sending", "the", "continue", "query", ...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L539-L560
train
rethinkdb/rethinkdb-go
cursor.go
handleError
func (c *Cursor) handleError(err error) error { c.mu.Lock() defer c.mu.Unlock() return c.handleErrorLocked(err) }
go
func (c *Cursor) handleError(err error) error { c.mu.Lock() defer c.mu.Unlock() return c.handleErrorLocked(err) }
[ "func", "(", "c", "*", "Cursor", ")", "handleError", "(", "err", "error", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "handleErrorLocked", "(", "err...
// handleError sets the value of lastErr to err if lastErr is not yet set.
[ "handleError", "sets", "the", "value", "of", "lastErr", "to", "err", "if", "lastErr", "is", "not", "yet", "set", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L563-L568
train
rethinkdb/rethinkdb-go
cursor.go
extend
func (c *Cursor) extend(response *Response) { c.mu.Lock() defer c.mu.Unlock() c.extendLocked(response) }
go
func (c *Cursor) extend(response *Response) { c.mu.Lock() defer c.mu.Unlock() c.extendLocked(response) }
[ "func", "(", "c", "*", "Cursor", ")", "extend", "(", "response", "*", "Response", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "c", ".", "extendLocked", "(", "response", ")", "...
// extend adds the result of a continue query to the cursor.
[ "extend", "adds", "the", "result", "of", "a", "continue", "query", "to", "the", "cursor", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L579-L584
train
rethinkdb/rethinkdb-go
cursor.go
seekCursor
func (c *Cursor) seekCursor(bufferResponse bool) error { if c.lastErr != nil { return c.lastErr } if len(c.buffer) == 0 && len(c.responses) == 0 && c.closed { return errCursorClosed } // Loop over loading data, applying skips as necessary and loading more data as needed // until either the cursor is closed or finished, or we have applied all outstanding // skips and data is available for { c.applyPendingSkips(bufferResponse) // if we are buffering the responses, skip can drain from the buffer if bufferResponse && len(c.buffer) == 0 && len(c.responses) > 0 { if err := c.bufferNextResponse(); err != nil { return err } continue // go around the loop again to re-apply pending skips } else if len(c.buffer) == 0 && len(c.responses) == 0 && !c.finished { // We skipped all of our data, load some more if err := c.fetchMore(); err != nil { return err } if c.closed { return nil } continue // go around the loop again to re-apply pending skips } return nil } }
go
func (c *Cursor) seekCursor(bufferResponse bool) error { if c.lastErr != nil { return c.lastErr } if len(c.buffer) == 0 && len(c.responses) == 0 && c.closed { return errCursorClosed } // Loop over loading data, applying skips as necessary and loading more data as needed // until either the cursor is closed or finished, or we have applied all outstanding // skips and data is available for { c.applyPendingSkips(bufferResponse) // if we are buffering the responses, skip can drain from the buffer if bufferResponse && len(c.buffer) == 0 && len(c.responses) > 0 { if err := c.bufferNextResponse(); err != nil { return err } continue // go around the loop again to re-apply pending skips } else if len(c.buffer) == 0 && len(c.responses) == 0 && !c.finished { // We skipped all of our data, load some more if err := c.fetchMore(); err != nil { return err } if c.closed { return nil } continue // go around the loop again to re-apply pending skips } return nil } }
[ "func", "(", "c", "*", "Cursor", ")", "seekCursor", "(", "bufferResponse", "bool", ")", "error", "{", "if", "c", ".", "lastErr", "!=", "nil", "{", "return", "c", ".", "lastErr", "\n", "}", "\n\n", "if", "len", "(", "c", ".", "buffer", ")", "==", ...
// seekCursor takes care of loading more data if needed and applying pending skips // // bufferResponse determines whether the response will be parsed into the buffer
[ "seekCursor", "takes", "care", "of", "loading", "more", "data", "if", "needed", "and", "applying", "pending", "skips", "bufferResponse", "determines", "whether", "the", "response", "will", "be", "parsed", "into", "the", "buffer" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L596-L628
train
rethinkdb/rethinkdb-go
cursor.go
applyPendingSkips
func (c *Cursor) applyPendingSkips(drainFromBuffer bool) (stillPending bool) { if c.pendingSkips == 0 { return false } if drainFromBuffer { if len(c.buffer) > c.pendingSkips { c.buffer = c.buffer[c.pendingSkips:] c.pendingSkips = 0 return false } c.pendingSkips -= len(c.buffer) c.buffer = c.buffer[:0] return c.pendingSkips > 0 } if len(c.responses) > c.pendingSkips { c.responses = c.responses[c.pendingSkips:] c.pendingSkips = 0 return false } c.pendingSkips -= len(c.responses) c.responses = c.responses[:0] return c.pendingSkips > 0 }
go
func (c *Cursor) applyPendingSkips(drainFromBuffer bool) (stillPending bool) { if c.pendingSkips == 0 { return false } if drainFromBuffer { if len(c.buffer) > c.pendingSkips { c.buffer = c.buffer[c.pendingSkips:] c.pendingSkips = 0 return false } c.pendingSkips -= len(c.buffer) c.buffer = c.buffer[:0] return c.pendingSkips > 0 } if len(c.responses) > c.pendingSkips { c.responses = c.responses[c.pendingSkips:] c.pendingSkips = 0 return false } c.pendingSkips -= len(c.responses) c.responses = c.responses[:0] return c.pendingSkips > 0 }
[ "func", "(", "c", "*", "Cursor", ")", "applyPendingSkips", "(", "drainFromBuffer", "bool", ")", "(", "stillPending", "bool", ")", "{", "if", "c", ".", "pendingSkips", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "if", "drainFromBuffer", "{", "if...
// applyPendingSkips applies all pending skips to the buffer and // returns whether there are more pending skips to be applied // // if drainFromBuffer is true, we will drain from the buffer, otherwise // we drain from the responses
[ "applyPendingSkips", "applies", "all", "pending", "skips", "to", "the", "buffer", "and", "returns", "whether", "there", "are", "more", "pending", "skips", "to", "be", "applied", "if", "drainFromBuffer", "is", "true", "we", "will", "drain", "from", "the", "buff...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L635-L661
train
rethinkdb/rethinkdb-go
cursor.go
bufferNextResponse
func (c *Cursor) bufferNextResponse() error { if c.closed { return errCursorClosed } // If there are no responses, nothing to do if len(c.responses) == 0 { return nil } response := c.responses[0] c.responses = c.responses[1:] var value interface{} decoder := json.NewDecoder(bytes.NewBuffer(response)) if c.connOpts.UseJSONNumber { decoder.UseNumber() } err := decoder.Decode(&value) if err != nil { return err } value, err = recursivelyConvertPseudotype(value, c.opts) if err != nil { return err } // If response is an ATOM then try and convert to an array if data, ok := value.([]interface{}); ok && c.isAtom { c.buffer = append(c.buffer, data...) } else if value == nil { c.buffer = append(c.buffer, nil) } else { c.buffer = append(c.buffer, value) // If this is the only value in the response and the response was an // atom then set the single value flag if c.isAtom { c.isSingleValue = true } } return nil }
go
func (c *Cursor) bufferNextResponse() error { if c.closed { return errCursorClosed } // If there are no responses, nothing to do if len(c.responses) == 0 { return nil } response := c.responses[0] c.responses = c.responses[1:] var value interface{} decoder := json.NewDecoder(bytes.NewBuffer(response)) if c.connOpts.UseJSONNumber { decoder.UseNumber() } err := decoder.Decode(&value) if err != nil { return err } value, err = recursivelyConvertPseudotype(value, c.opts) if err != nil { return err } // If response is an ATOM then try and convert to an array if data, ok := value.([]interface{}); ok && c.isAtom { c.buffer = append(c.buffer, data...) } else if value == nil { c.buffer = append(c.buffer, nil) } else { c.buffer = append(c.buffer, value) // If this is the only value in the response and the response was an // atom then set the single value flag if c.isAtom { c.isSingleValue = true } } return nil }
[ "func", "(", "c", "*", "Cursor", ")", "bufferNextResponse", "(", ")", "error", "{", "if", "c", ".", "closed", "{", "return", "errCursorClosed", "\n", "}", "\n", "// If there are no responses, nothing to do", "if", "len", "(", "c", ".", "responses", ")", "=="...
// bufferResponse reads a single response and stores the result into the buffer // if the response is from an atomic response, it will check if the // response contains multiple records and store them all into the buffer
[ "bufferResponse", "reads", "a", "single", "response", "and", "stores", "the", "result", "into", "the", "buffer", "if", "the", "response", "is", "from", "an", "atomic", "response", "it", "will", "check", "if", "the", "response", "contains", "multiple", "records...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cursor.go#L666-L708
train
rethinkdb/rethinkdb-go
query_manipulation.go
Field
func (t Term) Field(args ...interface{}) Term { return constructMethodTerm(t, "Field", p.Term_GET_FIELD, args, map[string]interface{}{}) }
go
func (t Term) Field(args ...interface{}) Term { return constructMethodTerm(t, "Field", p.Term_GET_FIELD, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Field", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_GET_FIELD", ",", "args", ",", "map", "[", "string", "]", "interface"...
// Field gets a single field from an object. If called on a sequence, gets that field // from every object in the sequence, skipping objects that lack it.
[ "Field", "gets", "a", "single", "field", "from", "an", "object", ".", "If", "called", "on", "a", "sequence", "gets", "that", "field", "from", "every", "object", "in", "the", "sequence", "skipping", "objects", "that", "lack", "it", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L22-L24
train
rethinkdb/rethinkdb-go
query_manipulation.go
Without
func (t Term) Without(args ...interface{}) Term { return constructMethodTerm(t, "Without", p.Term_WITHOUT, args, map[string]interface{}{}) }
go
func (t Term) Without(args ...interface{}) Term { return constructMethodTerm(t, "Without", p.Term_WITHOUT, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Without", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_WITHOUT", ",", "args", ",", "map", "[", "string", "]", "interface"...
// Without is the opposite of pluck; takes an object or a sequence of objects, and returns // them with the specified paths removed.
[ "Without", "is", "the", "opposite", "of", "pluck", ";", "takes", "an", "object", "or", "a", "sequence", "of", "objects", "and", "returns", "them", "with", "the", "specified", "paths", "removed", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L41-L43
train
rethinkdb/rethinkdb-go
query_manipulation.go
Merge
func (t Term) Merge(args ...interface{}) Term { return constructMethodTerm(t, "Merge", p.Term_MERGE, funcWrapArgs(args), map[string]interface{}{}) }
go
func (t Term) Merge(args ...interface{}) Term { return constructMethodTerm(t, "Merge", p.Term_MERGE, funcWrapArgs(args), map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Merge", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_MERGE", ",", "funcWrapArgs", "(", "args", ")", ",", "map", "[", "s...
// Merge merges two objects together to construct a new object with properties from both. // Gives preference to attributes from other when there is a conflict.
[ "Merge", "merges", "two", "objects", "together", "to", "construct", "a", "new", "object", "with", "properties", "from", "both", ".", "Gives", "preference", "to", "attributes", "from", "other", "when", "there", "is", "a", "conflict", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L47-L49
train
rethinkdb/rethinkdb-go
query_manipulation.go
Append
func (t Term) Append(args ...interface{}) Term { return constructMethodTerm(t, "Append", p.Term_APPEND, args, map[string]interface{}{}) }
go
func (t Term) Append(args ...interface{}) Term { return constructMethodTerm(t, "Append", p.Term_APPEND, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Append", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_APPEND", ",", "args", ",", "map", "[", "string", "]", "interface", ...
// Append appends a value to an array.
[ "Append", "appends", "a", "value", "to", "an", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L52-L54
train
rethinkdb/rethinkdb-go
query_manipulation.go
Prepend
func (t Term) Prepend(args ...interface{}) Term { return constructMethodTerm(t, "Prepend", p.Term_PREPEND, args, map[string]interface{}{}) }
go
func (t Term) Prepend(args ...interface{}) Term { return constructMethodTerm(t, "Prepend", p.Term_PREPEND, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Prepend", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_PREPEND", ",", "args", ",", "map", "[", "string", "]", "interface"...
// Prepend prepends a value to an array.
[ "Prepend", "prepends", "a", "value", "to", "an", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L57-L59
train
rethinkdb/rethinkdb-go
query_manipulation.go
Difference
func (t Term) Difference(args ...interface{}) Term { return constructMethodTerm(t, "Difference", p.Term_DIFFERENCE, args, map[string]interface{}{}) }
go
func (t Term) Difference(args ...interface{}) Term { return constructMethodTerm(t, "Difference", p.Term_DIFFERENCE, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Difference", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_DIFFERENCE", ",", "args", ",", "map", "[", "string", "]", "inte...
// Difference removes the elements of one array from another array.
[ "Difference", "removes", "the", "elements", "of", "one", "array", "from", "another", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L62-L64
train
rethinkdb/rethinkdb-go
query_manipulation.go
InsertAt
func (t Term) InsertAt(args ...interface{}) Term { return constructMethodTerm(t, "InsertAt", p.Term_INSERT_AT, args, map[string]interface{}{}) }
go
func (t Term) InsertAt(args ...interface{}) Term { return constructMethodTerm(t, "InsertAt", p.Term_INSERT_AT, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "InsertAt", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_INSERT_AT", ",", "args", ",", "map", "[", "string", "]", "interfa...
// InsertAt inserts a value in to an array at a given index. Returns the modified array.
[ "InsertAt", "inserts", "a", "value", "in", "to", "an", "array", "at", "a", "given", "index", ".", "Returns", "the", "modified", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L90-L92
train
rethinkdb/rethinkdb-go
query_manipulation.go
SpliceAt
func (t Term) SpliceAt(args ...interface{}) Term { return constructMethodTerm(t, "SpliceAt", p.Term_SPLICE_AT, args, map[string]interface{}{}) }
go
func (t Term) SpliceAt(args ...interface{}) Term { return constructMethodTerm(t, "SpliceAt", p.Term_SPLICE_AT, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "SpliceAt", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_SPLICE_AT", ",", "args", ",", "map", "[", "string", "]", "interfa...
// SpliceAt inserts several values in to an array at a given index. Returns the modified array.
[ "SpliceAt", "inserts", "several", "values", "in", "to", "an", "array", "at", "a", "given", "index", ".", "Returns", "the", "modified", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L95-L97
train
rethinkdb/rethinkdb-go
query_manipulation.go
DeleteAt
func (t Term) DeleteAt(args ...interface{}) Term { return constructMethodTerm(t, "DeleteAt", p.Term_DELETE_AT, args, map[string]interface{}{}) }
go
func (t Term) DeleteAt(args ...interface{}) Term { return constructMethodTerm(t, "DeleteAt", p.Term_DELETE_AT, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "DeleteAt", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_DELETE_AT", ",", "args", ",", "map", "[", "string", "]", "interfa...
// DeleteAt removes an element from an array at a given index. Returns the modified array.
[ "DeleteAt", "removes", "an", "element", "from", "an", "array", "at", "a", "given", "index", ".", "Returns", "the", "modified", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L100-L102
train
rethinkdb/rethinkdb-go
query_manipulation.go
ChangeAt
func (t Term) ChangeAt(args ...interface{}) Term { return constructMethodTerm(t, "ChangeAt", p.Term_CHANGE_AT, args, map[string]interface{}{}) }
go
func (t Term) ChangeAt(args ...interface{}) Term { return constructMethodTerm(t, "ChangeAt", p.Term_CHANGE_AT, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "ChangeAt", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_CHANGE_AT", ",", "args", ",", "map", "[", "string", "]", "interfa...
// ChangeAt changes a value in an array at a given index. Returns the modified array.
[ "ChangeAt", "changes", "a", "value", "in", "an", "array", "at", "a", "given", "index", ".", "Returns", "the", "modified", "array", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L105-L107
train
rethinkdb/rethinkdb-go
query_manipulation.go
Keys
func (t Term) Keys(args ...interface{}) Term { return constructMethodTerm(t, "Keys", p.Term_KEYS, args, map[string]interface{}{}) }
go
func (t Term) Keys(args ...interface{}) Term { return constructMethodTerm(t, "Keys", p.Term_KEYS, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Keys", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_KEYS", ",", "args", ",", "map", "[", "string", "]", "interface", "{...
// Keys returns an array containing all of the object's keys.
[ "Keys", "returns", "an", "array", "containing", "all", "of", "the", "object", "s", "keys", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_manipulation.go#L110-L112
train
rethinkdb/rethinkdb-go
pseudotypes.go
reqlTimeToNativeTime
func reqlTimeToNativeTime(timestamp float64, timezone string) (time.Time, error) { sec, ms := math.Modf(timestamp) // Convert to native time rounding to milliseconds t := time.Unix(int64(sec), int64(math.Floor(ms*1000+0.5))*1000*1000) // Caclulate the timezone if timezone != "" { hours, err := strconv.Atoi(timezone[1:3]) if err != nil { return time.Time{}, err } minutes, err := strconv.Atoi(timezone[4:6]) if err != nil { return time.Time{}, err } tzOffset := ((hours * 60) + minutes) * 60 if timezone[:1] == "-" { tzOffset = 0 - tzOffset } t = t.In(time.FixedZone(timezone, tzOffset)) } return t, nil }
go
func reqlTimeToNativeTime(timestamp float64, timezone string) (time.Time, error) { sec, ms := math.Modf(timestamp) // Convert to native time rounding to milliseconds t := time.Unix(int64(sec), int64(math.Floor(ms*1000+0.5))*1000*1000) // Caclulate the timezone if timezone != "" { hours, err := strconv.Atoi(timezone[1:3]) if err != nil { return time.Time{}, err } minutes, err := strconv.Atoi(timezone[4:6]) if err != nil { return time.Time{}, err } tzOffset := ((hours * 60) + minutes) * 60 if timezone[:1] == "-" { tzOffset = 0 - tzOffset } t = t.In(time.FixedZone(timezone, tzOffset)) } return t, nil }
[ "func", "reqlTimeToNativeTime", "(", "timestamp", "float64", ",", "timezone", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "sec", ",", "ms", ":=", "math", ".", "Modf", "(", "timestamp", ")", "\n\n", "// Convert to native time rounding to mi...
// Pseudo-type helper functions
[ "Pseudo", "-", "type", "helper", "functions" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/pseudotypes.go#L128-L153
train
rethinkdb/rethinkdb-go
query_write.go
Insert
func (t Term) Insert(arg interface{}, optArgs ...InsertOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Insert", p.Term_INSERT, []interface{}{Expr(arg)}, opts) }
go
func (t Term) Insert(arg interface{}, optArgs ...InsertOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Insert", p.Term_INSERT, []interface{}{Expr(arg)}, opts) }
[ "func", "(", "t", "Term", ")", "Insert", "(", "arg", "interface", "{", "}", ",", "optArgs", "...", "InsertOpts", ")", "Term", "{", "opts", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "len", "(", "optArgs", ")", "...
// Insert documents into a table. Accepts a single document or an array // of documents.
[ "Insert", "documents", "into", "a", "table", ".", "Accepts", "a", "single", "document", "or", "an", "array", "of", "documents", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_write.go#L20-L26
train
rethinkdb/rethinkdb-go
query_write.go
Update
func (t Term) Update(arg interface{}, optArgs ...UpdateOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Update", p.Term_UPDATE, []interface{}{funcWrap(arg)}, opts) }
go
func (t Term) Update(arg interface{}, optArgs ...UpdateOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Update", p.Term_UPDATE, []interface{}{funcWrap(arg)}, opts) }
[ "func", "(", "t", "Term", ")", "Update", "(", "arg", "interface", "{", "}", ",", "optArgs", "...", "UpdateOpts", ")", "Term", "{", "opts", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "len", "(", "optArgs", ")", "...
// Update JSON documents in a table. Accepts a JSON document, a ReQL expression, // or a combination of the two. You can pass options like returnChanges that will // return the old and new values of the row you have modified.
[ "Update", "JSON", "documents", "in", "a", "table", ".", "Accepts", "a", "JSON", "document", "a", "ReQL", "expression", "or", "a", "combination", "of", "the", "two", ".", "You", "can", "pass", "options", "like", "returnChanges", "that", "will", "return", "t...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_write.go#L43-L49
train
rethinkdb/rethinkdb-go
query_write.go
Replace
func (t Term) Replace(arg interface{}, optArgs ...ReplaceOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Replace", p.Term_REPLACE, []interface{}{funcWrap(arg)}, opts) }
go
func (t Term) Replace(arg interface{}, optArgs ...ReplaceOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Replace", p.Term_REPLACE, []interface{}{funcWrap(arg)}, opts) }
[ "func", "(", "t", "Term", ")", "Replace", "(", "arg", "interface", "{", "}", ",", "optArgs", "...", "ReplaceOpts", ")", "Term", "{", "opts", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "len", "(", "optArgs", ")", ...
// Replace documents in a table. Accepts a JSON document or a ReQL expression, // and replaces the original document with the new one. The new document must // have the same primary key as the original document.
[ "Replace", "documents", "in", "a", "table", ".", "Accepts", "a", "JSON", "document", "or", "a", "ReQL", "expression", "and", "replaces", "the", "original", "document", "with", "the", "new", "one", ".", "The", "new", "document", "must", "have", "the", "same...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_write.go#L65-L71
train
rethinkdb/rethinkdb-go
query_write.go
Delete
func (t Term) Delete(optArgs ...DeleteOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Delete", p.Term_DELETE, []interface{}{}, opts) }
go
func (t Term) Delete(optArgs ...DeleteOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "Delete", p.Term_DELETE, []interface{}{}, opts) }
[ "func", "(", "t", "Term", ")", "Delete", "(", "optArgs", "...", "DeleteOpts", ")", "Term", "{", "opts", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "len", "(", "optArgs", ")", ">=", "1", "{", "opts", "=", "optArg...
// Delete one or more documents from a table.
[ "Delete", "one", "or", "more", "documents", "from", "a", "table", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_write.go#L84-L90
train
rethinkdb/rethinkdb-go
query_write.go
Sync
func (t Term) Sync(args ...interface{}) Term { return constructMethodTerm(t, "Sync", p.Term_SYNC, args, map[string]interface{}{}) }
go
func (t Term) Sync(args ...interface{}) Term { return constructMethodTerm(t, "Sync", p.Term_SYNC, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Sync", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_SYNC", ",", "args", ",", "map", "[", "string", "]", "interface", "{...
// Sync ensures that writes on a given table are written to permanent storage. // Queries that specify soft durability do not give such guarantees, so Sync // can be used to ensure the state of these queries. A call to Sync does not // return until all previous writes to the table are persisted.
[ "Sync", "ensures", "that", "writes", "on", "a", "given", "table", "are", "written", "to", "permanent", "storage", ".", "Queries", "that", "specify", "soft", "durability", "do", "not", "give", "such", "guarantees", "so", "Sync", "can", "be", "used", "to", "...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_write.go#L96-L98
train
rethinkdb/rethinkdb-go
connection.go
NewConnection
func NewConnection(address string, opts *ConnectOpts) (*Connection, error) { keepAlivePeriod := defaultKeepAlivePeriod if opts.KeepAlivePeriod > 0 { keepAlivePeriod = opts.KeepAlivePeriod } // Connect to Server var err error var conn net.Conn nd := net.Dialer{Timeout: opts.Timeout, KeepAlive: keepAlivePeriod} if opts.TLSConfig == nil { conn, err = nd.Dial("tcp", address) } else { conn, err = tls.DialWithDialer(&nd, "tcp", address, opts.TLSConfig) } if err != nil { return nil, RQLConnectionError{rqlError(err.Error())} } c := newConnection(conn, address, opts) // Send handshake handshake, err := c.handshake(opts.HandshakeVersion) if err != nil { return nil, err } if err = handshake.Send(); err != nil { return nil, err } c.runConnection() return c, nil }
go
func NewConnection(address string, opts *ConnectOpts) (*Connection, error) { keepAlivePeriod := defaultKeepAlivePeriod if opts.KeepAlivePeriod > 0 { keepAlivePeriod = opts.KeepAlivePeriod } // Connect to Server var err error var conn net.Conn nd := net.Dialer{Timeout: opts.Timeout, KeepAlive: keepAlivePeriod} if opts.TLSConfig == nil { conn, err = nd.Dial("tcp", address) } else { conn, err = tls.DialWithDialer(&nd, "tcp", address, opts.TLSConfig) } if err != nil { return nil, RQLConnectionError{rqlError(err.Error())} } c := newConnection(conn, address, opts) // Send handshake handshake, err := c.handshake(opts.HandshakeVersion) if err != nil { return nil, err } if err = handshake.Send(); err != nil { return nil, err } c.runConnection() return c, nil }
[ "func", "NewConnection", "(", "address", "string", ",", "opts", "*", "ConnectOpts", ")", "(", "*", "Connection", ",", "error", ")", "{", "keepAlivePeriod", ":=", "defaultKeepAlivePeriod", "\n", "if", "opts", ".", "KeepAlivePeriod", ">", "0", "{", "keepAlivePer...
// NewConnection creates a new connection to the database server
[ "NewConnection", "creates", "a", "new", "connection", "to", "the", "database", "server" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/connection.go#L82-L116
train
rethinkdb/rethinkdb-go
connection.go
Close
func (c *Connection) Close() error { var err error c.mu.Lock() defer c.mu.Unlock() if !c.isClosed() { c.setClosed() close(c.stopReadChan) err = c.Conn.Close() } return err }
go
func (c *Connection) Close() error { var err error c.mu.Lock() defer c.mu.Unlock() if !c.isClosed() { c.setClosed() close(c.stopReadChan) err = c.Conn.Close() } return err }
[ "func", "(", "c", "*", "Connection", ")", "Close", "(", ")", "error", "{", "var", "err", "error", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "!", "c", ".", "isClosed", ...
// Close closes the underlying net.Conn
[ "Close", "closes", "the", "underlying", "net", ".", "Conn" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/connection.go#L139-L152
train
rethinkdb/rethinkdb-go
connection.go
Query
func (c *Connection) Query(ctx context.Context, q Query) (*Response, *Cursor, error) { if c == nil { return nil, nil, ErrConnectionClosed } if c.Conn == nil || c.isClosed() { c.setBad() return nil, nil, ErrConnectionClosed } if ctx == nil { ctx = c.contextFromConnectionOpts() } // Add token if query is a START/NOREPLY_WAIT if q.Type == p.Query_START || q.Type == p.Query_NOREPLY_WAIT || q.Type == p.Query_SERVER_INFO { q.Token = c.nextToken() } if q.Type == p.Query_START || q.Type == p.Query_NOREPLY_WAIT { if c.opts.Database != "" { var err error q.Opts["db"], err = DB(c.opts.Database).Build() if err != nil { return nil, nil, RQLDriverError{rqlError(err.Error())} } } } var fetchingSpan opentracing.Span if c.opts.UseOpentracing { parentSpan := opentracing.SpanFromContext(ctx) if parentSpan != nil { if q.Type == p.Query_START { querySpan := c.startTracingSpan(parentSpan, &q) // will be Finished when cursor closed parentSpan = querySpan ctx = opentracing.ContextWithSpan(ctx, querySpan) } fetchingSpan = c.startTracingSpan(parentSpan, &q) // will be Finished when response arrived } } err := c.sendQuery(q) if err != nil { if fetchingSpan != nil { ext.Error.Set(fetchingSpan, true) fetchingSpan.LogFields(log.Error(err)) fetchingSpan.Finish() if q.Type == p.Query_START { opentracing.SpanFromContext(ctx).Finish() } } return nil, nil, err } if noreply, ok := q.Opts["noreply"]; ok && noreply.(bool) { return nil, nil, nil } promise := make(chan responseAndCursor, 1) select { case c.readRequestsChan <- tokenAndPromise{ctx: ctx, query: &q, span: fetchingSpan, promise: promise}: case <-ctx.Done(): return c.stopQuery(&q) } select { case future := <-promise: return future.response, future.cursor, future.err case <-ctx.Done(): return c.stopQuery(&q) } }
go
func (c *Connection) Query(ctx context.Context, q Query) (*Response, *Cursor, error) { if c == nil { return nil, nil, ErrConnectionClosed } if c.Conn == nil || c.isClosed() { c.setBad() return nil, nil, ErrConnectionClosed } if ctx == nil { ctx = c.contextFromConnectionOpts() } // Add token if query is a START/NOREPLY_WAIT if q.Type == p.Query_START || q.Type == p.Query_NOREPLY_WAIT || q.Type == p.Query_SERVER_INFO { q.Token = c.nextToken() } if q.Type == p.Query_START || q.Type == p.Query_NOREPLY_WAIT { if c.opts.Database != "" { var err error q.Opts["db"], err = DB(c.opts.Database).Build() if err != nil { return nil, nil, RQLDriverError{rqlError(err.Error())} } } } var fetchingSpan opentracing.Span if c.opts.UseOpentracing { parentSpan := opentracing.SpanFromContext(ctx) if parentSpan != nil { if q.Type == p.Query_START { querySpan := c.startTracingSpan(parentSpan, &q) // will be Finished when cursor closed parentSpan = querySpan ctx = opentracing.ContextWithSpan(ctx, querySpan) } fetchingSpan = c.startTracingSpan(parentSpan, &q) // will be Finished when response arrived } } err := c.sendQuery(q) if err != nil { if fetchingSpan != nil { ext.Error.Set(fetchingSpan, true) fetchingSpan.LogFields(log.Error(err)) fetchingSpan.Finish() if q.Type == p.Query_START { opentracing.SpanFromContext(ctx).Finish() } } return nil, nil, err } if noreply, ok := q.Opts["noreply"]; ok && noreply.(bool) { return nil, nil, nil } promise := make(chan responseAndCursor, 1) select { case c.readRequestsChan <- tokenAndPromise{ctx: ctx, query: &q, span: fetchingSpan, promise: promise}: case <-ctx.Done(): return c.stopQuery(&q) } select { case future := <-promise: return future.response, future.cursor, future.err case <-ctx.Done(): return c.stopQuery(&q) } }
[ "func", "(", "c", "*", "Connection", ")", "Query", "(", "ctx", "context", ".", "Context", ",", "q", "Query", ")", "(", "*", "Response", ",", "*", "Cursor", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "return", "nil", ",", "nil", ",", "...
// Query sends a Query to the database, returning both the raw Response and a // Cursor which should be used to view the query's response. // // This function is used internally by Run which should be used for most queries.
[ "Query", "sends", "a", "Query", "to", "the", "database", "returning", "both", "the", "raw", "Response", "and", "a", "Cursor", "which", "should", "be", "used", "to", "view", "the", "query", "s", "response", ".", "This", "function", "is", "used", "internally...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/connection.go#L158-L228
train
rethinkdb/rethinkdb-go
connection.go
sendQuery
func (c *Connection) sendQuery(q Query) error { buf := &bytes.Buffer{} buf.Grow(respHeaderLen) buf.Write(buf.Bytes()[:respHeaderLen]) // reserve for header enc := json.NewEncoder(buf) // Build query err := enc.Encode(q.Build()) if err != nil { return RQLDriverError{rqlError(fmt.Sprintf("Error building query: %s", err.Error()))} } b := buf.Bytes() // Write header binary.LittleEndian.PutUint64(b, uint64(q.Token)) binary.LittleEndian.PutUint32(b[8:], uint32(len(b)-respHeaderLen)) // Set timeout if c.opts.WriteTimeout != 0 { c.Conn.SetWriteDeadline(time.Now().Add(c.opts.WriteTimeout)) } // Send the JSON encoding of the query itself. if err = c.writeData(b); err != nil { c.setBad() return RQLConnectionError{rqlError(err.Error())} } return nil }
go
func (c *Connection) sendQuery(q Query) error { buf := &bytes.Buffer{} buf.Grow(respHeaderLen) buf.Write(buf.Bytes()[:respHeaderLen]) // reserve for header enc := json.NewEncoder(buf) // Build query err := enc.Encode(q.Build()) if err != nil { return RQLDriverError{rqlError(fmt.Sprintf("Error building query: %s", err.Error()))} } b := buf.Bytes() // Write header binary.LittleEndian.PutUint64(b, uint64(q.Token)) binary.LittleEndian.PutUint32(b[8:], uint32(len(b)-respHeaderLen)) // Set timeout if c.opts.WriteTimeout != 0 { c.Conn.SetWriteDeadline(time.Now().Add(c.opts.WriteTimeout)) } // Send the JSON encoding of the query itself. if err = c.writeData(b); err != nil { c.setBad() return RQLConnectionError{rqlError(err.Error())} } return nil }
[ "func", "(", "c", "*", "Connection", ")", "sendQuery", "(", "q", "Query", ")", "error", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "buf", ".", "Grow", "(", "respHeaderLen", ")", "\n", "buf", ".", "Write", "(", "buf", ".", "Byt...
// sendQuery marshals the Query and sends the JSON to the server.
[ "sendQuery", "marshals", "the", "Query", "and", "sends", "the", "JSON", "to", "the", "server", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/connection.go#L363-L393
train
rethinkdb/rethinkdb-go
connection.go
readResponse
func (c *Connection) readResponse() (*Response, error) { // Set timeout if c.opts.ReadTimeout != 0 { c.Conn.SetReadDeadline(time.Now().Add(c.opts.ReadTimeout)) } // Read response header (token+length) headerBuf := [respHeaderLen]byte{} if _, err := c.read(headerBuf[:]); err != nil { c.setBad() return nil, RQLConnectionError{rqlError(err.Error())} } responseToken := int64(binary.LittleEndian.Uint64(headerBuf[:8])) messageLength := binary.LittleEndian.Uint32(headerBuf[8:]) // Read the JSON encoding of the Response itself. b := make([]byte, int(messageLength)) if _, err := c.read(b); err != nil { c.setBad() return nil, RQLConnectionError{rqlError(err.Error())} } // Decode the response var response = new(Response) if err := json.Unmarshal(b, response); err != nil { c.setBad() return nil, RQLDriverError{rqlError(err.Error())} } response.Token = responseToken return response, nil }
go
func (c *Connection) readResponse() (*Response, error) { // Set timeout if c.opts.ReadTimeout != 0 { c.Conn.SetReadDeadline(time.Now().Add(c.opts.ReadTimeout)) } // Read response header (token+length) headerBuf := [respHeaderLen]byte{} if _, err := c.read(headerBuf[:]); err != nil { c.setBad() return nil, RQLConnectionError{rqlError(err.Error())} } responseToken := int64(binary.LittleEndian.Uint64(headerBuf[:8])) messageLength := binary.LittleEndian.Uint32(headerBuf[8:]) // Read the JSON encoding of the Response itself. b := make([]byte, int(messageLength)) if _, err := c.read(b); err != nil { c.setBad() return nil, RQLConnectionError{rqlError(err.Error())} } // Decode the response var response = new(Response) if err := json.Unmarshal(b, response); err != nil { c.setBad() return nil, RQLDriverError{rqlError(err.Error())} } response.Token = responseToken return response, nil }
[ "func", "(", "c", "*", "Connection", ")", "readResponse", "(", ")", "(", "*", "Response", ",", "error", ")", "{", "// Set timeout", "if", "c", ".", "opts", ".", "ReadTimeout", "!=", "0", "{", "c", ".", "Conn", ".", "SetReadDeadline", "(", "time", "."...
// readResponse attempts to read a Response from the server, if no response // could be read then an error is returned.
[ "readResponse", "attempts", "to", "read", "a", "Response", "from", "the", "server", "if", "no", "response", "could", "be", "read", "then", "an", "error", "is", "returned", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/connection.go#L404-L437
train
rethinkdb/rethinkdb-go
connection.go
processResponse
func (c *Connection) processResponse(ctx context.Context, q Query, response *Response, span opentracing.Span) (r *Response, cur *Cursor, err error) { if span != nil { defer func() { if err != nil { ext.Error.Set(span, true) span.LogFields(log.Error(err)) } span.Finish() }() } switch response.Type { case p.Response_CLIENT_ERROR: return response, c.processErrorResponse(response), createClientError(response, q.Term) case p.Response_COMPILE_ERROR: return response, c.processErrorResponse(response), createCompileError(response, q.Term) case p.Response_RUNTIME_ERROR: return response, c.processErrorResponse(response), createRuntimeError(response.ErrorType, response, q.Term) case p.Response_SUCCESS_ATOM, p.Response_SERVER_INFO: return c.processAtomResponse(ctx, q, response) case p.Response_SUCCESS_PARTIAL: return c.processPartialResponse(ctx, q, response) case p.Response_SUCCESS_SEQUENCE: return c.processSequenceResponse(ctx, q, response) case p.Response_WAIT_COMPLETE: return c.processWaitResponse(response) default: return nil, nil, RQLDriverError{rqlError("Unexpected response type: %v")} } }
go
func (c *Connection) processResponse(ctx context.Context, q Query, response *Response, span opentracing.Span) (r *Response, cur *Cursor, err error) { if span != nil { defer func() { if err != nil { ext.Error.Set(span, true) span.LogFields(log.Error(err)) } span.Finish() }() } switch response.Type { case p.Response_CLIENT_ERROR: return response, c.processErrorResponse(response), createClientError(response, q.Term) case p.Response_COMPILE_ERROR: return response, c.processErrorResponse(response), createCompileError(response, q.Term) case p.Response_RUNTIME_ERROR: return response, c.processErrorResponse(response), createRuntimeError(response.ErrorType, response, q.Term) case p.Response_SUCCESS_ATOM, p.Response_SERVER_INFO: return c.processAtomResponse(ctx, q, response) case p.Response_SUCCESS_PARTIAL: return c.processPartialResponse(ctx, q, response) case p.Response_SUCCESS_SEQUENCE: return c.processSequenceResponse(ctx, q, response) case p.Response_WAIT_COMPLETE: return c.processWaitResponse(response) default: return nil, nil, RQLDriverError{rqlError("Unexpected response type: %v")} } }
[ "func", "(", "c", "*", "Connection", ")", "processResponse", "(", "ctx", "context", ".", "Context", ",", "q", "Query", ",", "response", "*", "Response", ",", "span", "opentracing", ".", "Span", ")", "(", "r", "*", "Response", ",", "cur", "*", "Cursor",...
// Called to fill response for the query
[ "Called", "to", "fill", "response", "for", "the", "query" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/connection.go#L440-L469
train
rethinkdb/rethinkdb-go
query_geospatial.go
ToGeoJSON
func (t Term) ToGeoJSON(args ...interface{}) Term { return constructMethodTerm(t, "ToGeoJSON", p.Term_TO_GEOJSON, args, map[string]interface{}{}) }
go
func (t Term) ToGeoJSON(args ...interface{}) Term { return constructMethodTerm(t, "ToGeoJSON", p.Term_TO_GEOJSON, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "ToGeoJSON", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_TO_GEOJSON", ",", "args", ",", "map", "[", "string", "]", "inter...
// ToGeoJSON converts a ReQL geometry object to a GeoJSON object.
[ "ToGeoJSON", "converts", "a", "ReQL", "geometry", "object", "to", "a", "GeoJSON", "object", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_geospatial.go#L76-L78
train
rethinkdb/rethinkdb-go
query_geospatial.go
GetIntersecting
func (t Term) GetIntersecting(args interface{}, optArgs ...GetIntersectingOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "GetIntersecting", p.Term_GET_INTERSECTING, []interface{}{args}, opts) }
go
func (t Term) GetIntersecting(args interface{}, optArgs ...GetIntersectingOpts) Term { opts := map[string]interface{}{} if len(optArgs) >= 1 { opts = optArgs[0].toMap() } return constructMethodTerm(t, "GetIntersecting", p.Term_GET_INTERSECTING, []interface{}{args}, opts) }
[ "func", "(", "t", "Term", ")", "GetIntersecting", "(", "args", "interface", "{", "}", ",", "optArgs", "...", "GetIntersectingOpts", ")", "Term", "{", "opts", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "len", "(", "o...
// GetIntersecting gets all documents where the given geometry object intersects // the geometry object of the requested geospatial index.
[ "GetIntersecting", "gets", "all", "documents", "where", "the", "given", "geometry", "object", "intersects", "the", "geometry", "object", "of", "the", "requested", "geospatial", "index", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_geospatial.go#L91-L98
train
rethinkdb/rethinkdb-go
query_geospatial.go
Includes
func (t Term) Includes(args ...interface{}) Term { return constructMethodTerm(t, "Includes", p.Term_INCLUDES, args, map[string]interface{}{}) }
go
func (t Term) Includes(args ...interface{}) Term { return constructMethodTerm(t, "Includes", p.Term_INCLUDES, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Includes", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_INCLUDES", ",", "args", ",", "map", "[", "string", "]", "interfac...
// Includes tests whether a geometry object is completely contained within another. // When applied to a sequence of geometry objects, includes acts as a filter, // returning a sequence of objects from the sequence that include the argument.
[ "Includes", "tests", "whether", "a", "geometry", "object", "is", "completely", "contained", "within", "another", ".", "When", "applied", "to", "a", "sequence", "of", "geometry", "objects", "includes", "acts", "as", "a", "filter", "returning", "a", "sequence", ...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_geospatial.go#L127-L129
train
rethinkdb/rethinkdb-go
query_geospatial.go
Intersects
func (t Term) Intersects(args ...interface{}) Term { return constructMethodTerm(t, "Intersects", p.Term_INTERSECTS, args, map[string]interface{}{}) }
go
func (t Term) Intersects(args ...interface{}) Term { return constructMethodTerm(t, "Intersects", p.Term_INTERSECTS, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Intersects", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_INTERSECTS", ",", "args", ",", "map", "[", "string", "]", "inte...
// Intersects tests whether two geometry objects intersect with one another. // When applied to a sequence of geometry objects, intersects acts as a filter, // returning a sequence of objects from the sequence that intersect with the // argument.
[ "Intersects", "tests", "whether", "two", "geometry", "objects", "intersect", "with", "one", "another", ".", "When", "applied", "to", "a", "sequence", "of", "geometry", "objects", "intersects", "acts", "as", "a", "filter", "returning", "a", "sequence", "of", "o...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_geospatial.go#L135-L137
train
rethinkdb/rethinkdb-go
query_select.go
Get
func (t Term) Get(args ...interface{}) Term { return constructMethodTerm(t, "Get", p.Term_GET, args, map[string]interface{}{}) }
go
func (t Term) Get(args ...interface{}) Term { return constructMethodTerm(t, "Get", p.Term_GET, args, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "Get", "(", "args", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_GET", ",", "args", ",", "map", "[", "string", "]", "interface", "{",...
// Get gets a document by primary key. If nothing was found, RethinkDB will return a nil value.
[ "Get", "gets", "a", "document", "by", "primary", "key", ".", "If", "nothing", "was", "found", "RethinkDB", "will", "return", "a", "nil", "value", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_select.go#L60-L62
train
rethinkdb/rethinkdb-go
query_select.go
GetAll
func (t Term) GetAll(keys ...interface{}) Term { return constructMethodTerm(t, "GetAll", p.Term_GET_ALL, keys, map[string]interface{}{}) }
go
func (t Term) GetAll(keys ...interface{}) Term { return constructMethodTerm(t, "GetAll", p.Term_GET_ALL, keys, map[string]interface{}{}) }
[ "func", "(", "t", "Term", ")", "GetAll", "(", "keys", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_GET_ALL", ",", "keys", ",", "map", "[", "string", "]", "interface",...
// GetAll gets all documents where the given value matches the value of the primary // index. Multiple values can be passed this function if you want to select multiple // documents. If the documents you are fetching have composite keys then each // argument should be a slice. For more information see the examples.
[ "GetAll", "gets", "all", "documents", "where", "the", "given", "value", "matches", "the", "value", "of", "the", "primary", "index", ".", "Multiple", "values", "can", "be", "passed", "this", "function", "if", "you", "want", "to", "select", "multiple", "docume...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_select.go#L77-L79
train
rethinkdb/rethinkdb-go
query_select.go
GetAllByIndex
func (t Term) GetAllByIndex(index interface{}, keys ...interface{}) Term { return constructMethodTerm(t, "GetAll", p.Term_GET_ALL, keys, map[string]interface{}{"index": index}) }
go
func (t Term) GetAllByIndex(index interface{}, keys ...interface{}) Term { return constructMethodTerm(t, "GetAll", p.Term_GET_ALL, keys, map[string]interface{}{"index": index}) }
[ "func", "(", "t", "Term", ")", "GetAllByIndex", "(", "index", "interface", "{", "}", ",", "keys", "...", "interface", "{", "}", ")", "Term", "{", "return", "constructMethodTerm", "(", "t", ",", "\"", "\"", ",", "p", ".", "Term_GET_ALL", ",", "keys", ...
// GetAllByIndex gets all documents where the given value matches the value of // the requested index.
[ "GetAllByIndex", "gets", "all", "documents", "where", "the", "given", "value", "matches", "the", "value", "of", "the", "requested", "index", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/query_select.go#L83-L85
train
rethinkdb/rethinkdb-go
cluster.go
NewCluster
func NewCluster(hosts []Host, opts *ConnectOpts) (*Cluster, error) { c := &Cluster{ hp: hostpool.NewEpsilonGreedy([]string{}, opts.HostDecayDuration, &hostpool.LinearEpsilonValueCalculator{}), seeds: hosts, opts: opts, } // Attempt to connect to each host and discover any additional hosts if host // discovery is enabled if err := c.connectNodes(c.getSeeds()); err != nil { return nil, err } if !c.IsConnected() { return nil, ErrNoConnectionsStarted } if opts.DiscoverHosts { go c.discover() } return c, nil }
go
func NewCluster(hosts []Host, opts *ConnectOpts) (*Cluster, error) { c := &Cluster{ hp: hostpool.NewEpsilonGreedy([]string{}, opts.HostDecayDuration, &hostpool.LinearEpsilonValueCalculator{}), seeds: hosts, opts: opts, } // Attempt to connect to each host and discover any additional hosts if host // discovery is enabled if err := c.connectNodes(c.getSeeds()); err != nil { return nil, err } if !c.IsConnected() { return nil, ErrNoConnectionsStarted } if opts.DiscoverHosts { go c.discover() } return c, nil }
[ "func", "NewCluster", "(", "hosts", "[", "]", "Host", ",", "opts", "*", "ConnectOpts", ")", "(", "*", "Cluster", ",", "error", ")", "{", "c", ":=", "&", "Cluster", "{", "hp", ":", "hostpool", ".", "NewEpsilonGreedy", "(", "[", "]", "string", "{", "...
// NewCluster creates a new cluster by connecting to the given hosts.
[ "NewCluster", "creates", "a", "new", "cluster", "by", "connecting", "to", "the", "given", "hosts", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L36-L58
train
rethinkdb/rethinkdb-go
cluster.go
Query
func (c *Cluster) Query(ctx context.Context, q Query) (cursor *Cursor, err error) { for i := 0; i < c.numRetries(); i++ { var node *Node var hpr hostpool.HostPoolResponse node, hpr, err = c.GetNextNode() if err != nil { return nil, err } cursor, err = node.Query(ctx, q) hpr.Mark(err) if !shouldRetryQuery(q, err) { break } } return cursor, err }
go
func (c *Cluster) Query(ctx context.Context, q Query) (cursor *Cursor, err error) { for i := 0; i < c.numRetries(); i++ { var node *Node var hpr hostpool.HostPoolResponse node, hpr, err = c.GetNextNode() if err != nil { return nil, err } cursor, err = node.Query(ctx, q) hpr.Mark(err) if !shouldRetryQuery(q, err) { break } } return cursor, err }
[ "func", "(", "c", "*", "Cluster", ")", "Query", "(", "ctx", "context", ".", "Context", ",", "q", "Query", ")", "(", "cursor", "*", "Cursor", ",", "err", "error", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "c", ".", "numRetries", "(", ")", ...
// Query executes a ReQL query using the cluster to connect to the database
[ "Query", "executes", "a", "ReQL", "query", "using", "the", "cluster", "to", "connect", "to", "the", "database" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L61-L80
train
rethinkdb/rethinkdb-go
cluster.go
Close
func (c *Cluster) Close(optArgs ...CloseOpts) error { if c.closed { return nil } for _, node := range c.GetNodes() { err := node.Close(optArgs...) if err != nil { return err } } c.hp.Close() c.closed = true return nil }
go
func (c *Cluster) Close(optArgs ...CloseOpts) error { if c.closed { return nil } for _, node := range c.GetNodes() { err := node.Close(optArgs...) if err != nil { return err } } c.hp.Close() c.closed = true return nil }
[ "func", "(", "c", "*", "Cluster", ")", "Close", "(", "optArgs", "...", "CloseOpts", ")", "error", "{", "if", "c", ".", "closed", "{", "return", "nil", "\n", "}", "\n\n", "for", "_", ",", "node", ":=", "range", "c", ".", "GetNodes", "(", ")", "{",...
// Close closes the cluster
[ "Close", "closes", "the", "cluster" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L150-L166
train
rethinkdb/rethinkdb-go
cluster.go
discover
func (c *Cluster) discover() { // Keep retrying with exponential backoff. b := backoff.NewExponentialBackOff() // Never finish retrying (max interval is still 60s) b.MaxElapsedTime = 0 // Keep trying to discover new nodes for { backoff.RetryNotify(func() error { // If no hosts try seeding nodes if len(c.GetNodes()) == 0 { c.connectNodes(c.getSeeds()) } return c.listenForNodeChanges() }, b, func(err error, wait time.Duration) { Log.Debugf("Error discovering hosts %s, waiting: %s", err, wait) }) } }
go
func (c *Cluster) discover() { // Keep retrying with exponential backoff. b := backoff.NewExponentialBackOff() // Never finish retrying (max interval is still 60s) b.MaxElapsedTime = 0 // Keep trying to discover new nodes for { backoff.RetryNotify(func() error { // If no hosts try seeding nodes if len(c.GetNodes()) == 0 { c.connectNodes(c.getSeeds()) } return c.listenForNodeChanges() }, b, func(err error, wait time.Duration) { Log.Debugf("Error discovering hosts %s, waiting: %s", err, wait) }) } }
[ "func", "(", "c", "*", "Cluster", ")", "discover", "(", ")", "{", "// Keep retrying with exponential backoff.", "b", ":=", "backoff", ".", "NewExponentialBackOff", "(", ")", "\n", "// Never finish retrying (max interval is still 60s)", "b", ".", "MaxElapsedTime", "=", ...
// discover attempts to find new nodes in the cluster using the current nodes
[ "discover", "attempts", "to", "find", "new", "nodes", "in", "the", "cluster", "using", "the", "current", "nodes" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L169-L188
train
rethinkdb/rethinkdb-go
cluster.go
listenForNodeChanges
func (c *Cluster) listenForNodeChanges() error { // Start listening to changes from a random active node node, hpr, err := c.GetNextNode() if err != nil { return err } q, err := newQuery( DB("rethinkdb").Table("server_status").Changes(), map[string]interface{}{}, c.opts, ) if err != nil { return fmt.Errorf("Error building query: %s", err) } cursor, err := node.Query(context.Background(), q) // no need for timeout due to Changes() if err != nil { hpr.Mark(err) return err } // Keep reading node status updates from changefeed var result struct { NewVal nodeStatus `rethinkdb:"new_val"` OldVal nodeStatus `rethinkdb:"old_val"` } for cursor.Next(&result) { addr := fmt.Sprintf("%s:%d", result.NewVal.Network.Hostname, result.NewVal.Network.ReqlPort) addr = strings.ToLower(addr) switch result.NewVal.Status { case "connected": // Connect to node using exponential backoff (give up after waiting 5s) // to give the node time to start-up. b := backoff.NewExponentialBackOff() b.MaxElapsedTime = time.Second * 5 backoff.Retry(func() error { node, err := c.connectNodeWithStatus(result.NewVal) if err == nil { if !c.nodeExists(node) { c.addNode(node) Log.WithFields(logrus.Fields{ "id": node.ID, "host": node.Host.String(), }).Debug("Connected to node") } } return err }, b) } } err = cursor.Err() hpr.Mark(err) return err }
go
func (c *Cluster) listenForNodeChanges() error { // Start listening to changes from a random active node node, hpr, err := c.GetNextNode() if err != nil { return err } q, err := newQuery( DB("rethinkdb").Table("server_status").Changes(), map[string]interface{}{}, c.opts, ) if err != nil { return fmt.Errorf("Error building query: %s", err) } cursor, err := node.Query(context.Background(), q) // no need for timeout due to Changes() if err != nil { hpr.Mark(err) return err } // Keep reading node status updates from changefeed var result struct { NewVal nodeStatus `rethinkdb:"new_val"` OldVal nodeStatus `rethinkdb:"old_val"` } for cursor.Next(&result) { addr := fmt.Sprintf("%s:%d", result.NewVal.Network.Hostname, result.NewVal.Network.ReqlPort) addr = strings.ToLower(addr) switch result.NewVal.Status { case "connected": // Connect to node using exponential backoff (give up after waiting 5s) // to give the node time to start-up. b := backoff.NewExponentialBackOff() b.MaxElapsedTime = time.Second * 5 backoff.Retry(func() error { node, err := c.connectNodeWithStatus(result.NewVal) if err == nil { if !c.nodeExists(node) { c.addNode(node) Log.WithFields(logrus.Fields{ "id": node.ID, "host": node.Host.String(), }).Debug("Connected to node") } } return err }, b) } } err = cursor.Err() hpr.Mark(err) return err }
[ "func", "(", "c", "*", "Cluster", ")", "listenForNodeChanges", "(", ")", "error", "{", "// Start listening to changes from a random active node", "node", ",", "hpr", ",", "err", ":=", "c", ".", "GetNextNode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "r...
// listenForNodeChanges listens for changes to node status using change feeds. // This function will block until the query fails
[ "listenForNodeChanges", "listens", "for", "changes", "to", "node", "status", "using", "change", "feeds", ".", "This", "function", "will", "block", "until", "the", "query", "fails" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L192-L251
train
rethinkdb/rethinkdb-go
cluster.go
AddSeeds
func (c *Cluster) AddSeeds(hosts []Host) { c.mu.Lock() c.seeds = append(c.seeds, hosts...) c.mu.Unlock() }
go
func (c *Cluster) AddSeeds(hosts []Host) { c.mu.Lock() c.seeds = append(c.seeds, hosts...) c.mu.Unlock() }
[ "func", "(", "c", "*", "Cluster", ")", "AddSeeds", "(", "hosts", "[", "]", "Host", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "c", ".", "seeds", "=", "append", "(", "c", ".", "seeds", ",", "hosts", "...", ")", "\n", "c", ".", "m...
// AddSeeds adds new seed hosts to the cluster.
[ "AddSeeds", "adds", "new", "seed", "hosts", "to", "the", "cluster", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L403-L407
train
rethinkdb/rethinkdb-go
cluster.go
GetNextNode
func (c *Cluster) GetNextNode() (*Node, hostpool.HostPoolResponse, error) { if !c.IsConnected() { return nil, nil, ErrNoConnections } c.mu.RLock() defer c.mu.RUnlock() nodes := c.nodes hpr := c.hp.Get() if n, ok := nodes[hpr.Host()]; ok { if !n.Closed() { return n, hpr, nil } } return nil, nil, ErrNoConnections }
go
func (c *Cluster) GetNextNode() (*Node, hostpool.HostPoolResponse, error) { if !c.IsConnected() { return nil, nil, ErrNoConnections } c.mu.RLock() defer c.mu.RUnlock() nodes := c.nodes hpr := c.hp.Get() if n, ok := nodes[hpr.Host()]; ok { if !n.Closed() { return n, hpr, nil } } return nil, nil, ErrNoConnections }
[ "func", "(", "c", "*", "Cluster", ")", "GetNextNode", "(", ")", "(", "*", "Node", ",", "hostpool", ".", "HostPoolResponse", ",", "error", ")", "{", "if", "!", "c", ".", "IsConnected", "(", ")", "{", "return", "nil", ",", "nil", ",", "ErrNoConnections...
// GetNextNode returns a random node on the cluster
[ "GetNextNode", "returns", "a", "random", "node", "on", "the", "cluster" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L418-L434
train
rethinkdb/rethinkdb-go
cluster.go
GetNodes
func (c *Cluster) GetNodes() []*Node { c.mu.RLock() nodes := make([]*Node, 0, len(c.nodes)) for _, n := range c.nodes { nodes = append(nodes, n) } c.mu.RUnlock() return nodes }
go
func (c *Cluster) GetNodes() []*Node { c.mu.RLock() nodes := make([]*Node, 0, len(c.nodes)) for _, n := range c.nodes { nodes = append(nodes, n) } c.mu.RUnlock() return nodes }
[ "func", "(", "c", "*", "Cluster", ")", "GetNodes", "(", ")", "[", "]", "*", "Node", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "nodes", ":=", "make", "(", "[", "]", "*", "Node", ",", "0", ",", "len", "(", "c", ".", "nodes", ")", "...
// GetNodes returns a list of all nodes in the cluster
[ "GetNodes", "returns", "a", "list", "of", "all", "nodes", "in", "the", "cluster" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/cluster.go#L437-L446
train
rethinkdb/rethinkdb-go
session.go
IsConnected
func (s *Session) IsConnected() bool { s.mu.RLock() defer s.mu.RUnlock() if s.cluster == nil || s.closed { return false } return s.cluster.IsConnected() }
go
func (s *Session) IsConnected() bool { s.mu.RLock() defer s.mu.RUnlock() if s.cluster == nil || s.closed { return false } return s.cluster.IsConnected() }
[ "func", "(", "s", "*", "Session", ")", "IsConnected", "(", ")", "bool", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "if", "s", ".", "cluster", "==", "nil", "||", "s", ".", "clo...
// IsConnected returns true if session has a valid connection.
[ "IsConnected", "returns", "true", "if", "session", "has", "a", "valid", "connection", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/session.go#L178-L186
train
rethinkdb/rethinkdb-go
session.go
Reconnect
func (s *Session) Reconnect(optArgs ...CloseOpts) error { var err error if err = s.Close(optArgs...); err != nil { return err } s.mu.Lock() s.cluster, err = NewCluster(s.hosts, s.opts) if err != nil { s.mu.Unlock() return err } s.closed = false s.mu.Unlock() return nil }
go
func (s *Session) Reconnect(optArgs ...CloseOpts) error { var err error if err = s.Close(optArgs...); err != nil { return err } s.mu.Lock() s.cluster, err = NewCluster(s.hosts, s.opts) if err != nil { s.mu.Unlock() return err } s.closed = false s.mu.Unlock() return nil }
[ "func", "(", "s", "*", "Session", ")", "Reconnect", "(", "optArgs", "...", "CloseOpts", ")", "error", "{", "var", "err", "error", "\n\n", "if", "err", "=", "s", ".", "Close", "(", "optArgs", "...", ")", ";", "err", "!=", "nil", "{", "return", "err"...
// Reconnect closes and re-opens a session.
[ "Reconnect", "closes", "and", "re", "-", "opens", "a", "session", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/session.go#L189-L207
train
rethinkdb/rethinkdb-go
session.go
Use
func (s *Session) Use(database string) { s.mu.Lock() defer s.mu.Unlock() s.opts.Database = database }
go
func (s *Session) Use(database string) { s.mu.Lock() defer s.mu.Unlock() s.opts.Database = database }
[ "func", "(", "s", "*", "Session", ")", "Use", "(", "database", "string", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "opts", ".", "Database", "=", "database", "\n", ...
// Use changes the default database used
[ "Use", "changes", "the", "default", "database", "used" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/session.go#L280-L285
train
rethinkdb/rethinkdb-go
session.go
Database
func (s *Session) Database() string { s.mu.RLock() defer s.mu.RUnlock() return s.opts.Database }
go
func (s *Session) Database() string { s.mu.RLock() defer s.mu.RUnlock() return s.opts.Database }
[ "func", "(", "s", "*", "Session", ")", "Database", "(", ")", "string", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "opts", ".", "Database", "\n", "}" ]
// Database returns the selected database set by Use
[ "Database", "returns", "the", "selected", "database", "set", "by", "Use" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/session.go#L288-L293
train
rethinkdb/rethinkdb-go
session.go
Query
func (s *Session) Query(ctx context.Context, q Query) (*Cursor, error) { s.mu.RLock() defer s.mu.RUnlock() if s.closed { return nil, ErrConnectionClosed } return s.cluster.Query(ctx, q) }
go
func (s *Session) Query(ctx context.Context, q Query) (*Cursor, error) { s.mu.RLock() defer s.mu.RUnlock() if s.closed { return nil, ErrConnectionClosed } return s.cluster.Query(ctx, q) }
[ "func", "(", "s", "*", "Session", ")", "Query", "(", "ctx", "context", ".", "Context", ",", "q", "Query", ")", "(", "*", "Cursor", ",", "error", ")", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", ...
// Query executes a ReQL query using the session to connect to the database
[ "Query", "executes", "a", "ReQL", "query", "using", "the", "session", "to", "connect", "to", "the", "database" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/session.go#L296-L305
train
rethinkdb/rethinkdb-go
session.go
SetHosts
func (s *Session) SetHosts(hosts []Host) { s.mu.Lock() defer s.mu.Unlock() s.hosts = hosts }
go
func (s *Session) SetHosts(hosts []Host) { s.mu.Lock() defer s.mu.Unlock() s.hosts = hosts }
[ "func", "(", "s", "*", "Session", ")", "SetHosts", "(", "hosts", "[", "]", "Host", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "hosts", "=", "hosts", "\n", "}" ]
// SetHosts resets the hosts used when connecting to the RethinkDB cluster
[ "SetHosts", "resets", "the", "hosts", "used", "when", "connecting", "to", "the", "RethinkDB", "cluster" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/session.go#L325-L330
train
rethinkdb/rethinkdb-go
pool.go
NewPool
func NewPool(host Host, opts *ConnectOpts) (*Pool, error) { initialCap := opts.InitialCap if initialCap <= 0 { // Fallback to MaxIdle if InitialCap is zero, this should be removed // when MaxIdle is removed initialCap = opts.MaxIdle } maxOpen := opts.MaxOpen if maxOpen <= 0 { maxOpen = 2 } p, err := pool.NewChannelPool(initialCap, maxOpen, func() (net.Conn, error) { conn, err := NewConnection(host.String(), opts) if err != nil { return nil, err } return conn, err }) if err != nil { return nil, err } return &Pool{ pool: p, host: host, opts: opts, }, nil }
go
func NewPool(host Host, opts *ConnectOpts) (*Pool, error) { initialCap := opts.InitialCap if initialCap <= 0 { // Fallback to MaxIdle if InitialCap is zero, this should be removed // when MaxIdle is removed initialCap = opts.MaxIdle } maxOpen := opts.MaxOpen if maxOpen <= 0 { maxOpen = 2 } p, err := pool.NewChannelPool(initialCap, maxOpen, func() (net.Conn, error) { conn, err := NewConnection(host.String(), opts) if err != nil { return nil, err } return conn, err }) if err != nil { return nil, err } return &Pool{ pool: p, host: host, opts: opts, }, nil }
[ "func", "NewPool", "(", "host", "Host", ",", "opts", "*", "ConnectOpts", ")", "(", "*", "Pool", ",", "error", ")", "{", "initialCap", ":=", "opts", ".", "InitialCap", "\n", "if", "initialCap", "<=", "0", "{", "// Fallback to MaxIdle if InitialCap is zero, this...
// NewPool creates a new connection pool for the given host
[ "NewPool", "creates", "a", "new", "connection", "pool", "for", "the", "given", "host" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/pool.go#L29-L59
train
rethinkdb/rethinkdb-go
pool.go
Close
func (p *Pool) Close() error { p.mu.RLock() defer p.mu.RUnlock() if p.closed { return nil } p.pool.Close() return nil }
go
func (p *Pool) Close() error { p.mu.RLock() defer p.mu.RUnlock() if p.closed { return nil } p.pool.Close() return nil }
[ "func", "(", "p", "*", "Pool", ")", "Close", "(", ")", "error", "{", "p", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "p", ".", "closed", "{", "return", "nil", "\n", "}", "\n\n", "...
// Close closes the database, releasing any open resources. // // It is rare to Close a Pool, as the Pool handle is meant to be // long-lived and shared between many goroutines.
[ "Close", "closes", "the", "database", "releasing", "any", "open", "resources", ".", "It", "is", "rare", "to", "Close", "a", "Pool", "as", "the", "Pool", "handle", "is", "meant", "to", "be", "long", "-", "lived", "and", "shared", "between", "many", "gorou...
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/pool.go#L75-L85
train
rethinkdb/rethinkdb-go
pool.go
Exec
func (p *Pool) Exec(ctx context.Context, q Query) error { c, pc, err := p.conn() if err != nil { return err } defer pc.Close() _, _, err = c.Query(ctx, q) if c.isBad() { pc.MarkUnusable() } return err }
go
func (p *Pool) Exec(ctx context.Context, q Query) error { c, pc, err := p.conn() if err != nil { return err } defer pc.Close() _, _, err = c.Query(ctx, q) if c.isBad() { pc.MarkUnusable() } return err }
[ "func", "(", "p", "*", "Pool", ")", "Exec", "(", "ctx", "context", ".", "Context", ",", "q", "Query", ")", "error", "{", "c", ",", "pc", ",", "err", ":=", "p", ".", "conn", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n",...
// Query execution functions // Exec executes a query without waiting for any response.
[ "Query", "execution", "functions", "Exec", "executes", "a", "query", "without", "waiting", "for", "any", "response", "." ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/pool.go#L140-L154
train
rethinkdb/rethinkdb-go
pool.go
Query
func (p *Pool) Query(ctx context.Context, q Query) (*Cursor, error) { c, pc, err := p.conn() if err != nil { return nil, err } _, cursor, err := c.Query(ctx, q) if err == nil { cursor.releaseConn = releaseConn(c, pc) } else { if c.isBad() { pc.MarkUnusable() } pc.Close() } return cursor, err }
go
func (p *Pool) Query(ctx context.Context, q Query) (*Cursor, error) { c, pc, err := p.conn() if err != nil { return nil, err } _, cursor, err := c.Query(ctx, q) if err == nil { cursor.releaseConn = releaseConn(c, pc) } else { if c.isBad() { pc.MarkUnusable() } pc.Close() } return cursor, err }
[ "func", "(", "p", "*", "Pool", ")", "Query", "(", "ctx", "context", ".", "Context", ",", "q", "Query", ")", "(", "*", "Cursor", ",", "error", ")", "{", "c", ",", "pc", ",", "err", ":=", "p", ".", "conn", "(", ")", "\n", "if", "err", "!=", "...
// Query executes a query and waits for the response
[ "Query", "executes", "a", "query", "and", "waits", "for", "the", "response" ]
04a849766900ad9c936ba78770186640e3bede20
https://github.com/rethinkdb/rethinkdb-go/blob/04a849766900ad9c936ba78770186640e3bede20/pool.go#L157-L175
train