_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q174000
ApiClient
validation
func (c *Client) ApiClient(identifier string) (*ApiClient, error) { apiClient := new(ApiClient) _, err := c.MakeApiRequest("GET", "/1.0/api_clients/"+identifier, nil, apiClient) if err != nil { return nil, err } return apiClient, err }
go
{ "resource": "" }
q174001
ResetSecretForApiClient
validation
func (c *Client) ResetSecretForApiClient(identifier string) (*ApiClient, error) { ac := new(ApiClient) _, err := c.MakeApiRequest("POST", "/1.0/api_clients/"+identifier+"/reset_secret", nil, &ac) if err != nil { return nil, err } return ac, nil }
go
{ "resource": "" }
q174002
Images
validation
func (c *Client) Images() ([]Image, error) { var images []Image _, err := c.MakeApiRequest("GET", "/1.0/images", nil, &images) if err != nil { return nil, err } return images, err }
go
{ "resource": "" }
q174003
Image
validation
func (c *Client) Image(identifier string) (*Image, error) { image := new(Image) _, err := c.MakeApiRequest("GET", "/1.0/images/"+identifier, nil, image) if err != nil { return nil, err } return image, err }
go
{ "resource": "" }
q174004
Accounts
validation
func (c *Client) Accounts() ([]Account, error) { var accounts []Account _, err := c.MakeApiRequest("GET", "/1.0/accounts?nested=false", nil, &accounts) if err != nil { return nil, err } return accounts, err }
go
{ "resource": "" }
q174005
Account
validation
func (c *Client) Account(identifier string) (*Account, error) { account := new(Account) _, err := c.MakeApiRequest("GET", "/1.0/accounts/"+identifier, nil, account) if err != nil { return nil, err } return account, err }
go
{ "resource": "" }
q174006
CloudIPs
validation
func (c *Client) CloudIPs() ([]CloudIP, error) { var cloudips []CloudIP _, err := c.MakeApiRequest("GET", "/1.0/cloud_ips", nil, &cloudips) if err != nil { return nil, err } return cloudips, err }
go
{ "resource": "" }
q174007
CloudIP
validation
func (c *Client) CloudIP(identifier string) (*CloudIP, error) { cloudip := new(CloudIP) _, err := c.MakeApiRequest("GET", "/1.0/cloud_ips/"+identifier, nil, cloudip) if err != nil { return nil, err } return cloudip, err }
go
{ "resource": "" }
q174008
MapCloudIPtoServer
validation
func (c *Client) MapCloudIPtoServer(identifier string, serverid string) error { server, err := c.Server(serverid) if err != nil { return err } if len(server.Interfaces) == 0 { return fmt.Errorf("Server %s has no interfaces to map cloud ip %s to", server.Id, identifier) } destination := server.Interfaces[0].Id...
go
{ "resource": "" }
q174009
setAuthHeader
validation
func setAuthHeader(t *oauth2.Token, r *http.Request) { r.Header.Set("X-Auth-Token", t.AccessToken) }
go
{ "resource": "" }
q174010
Auth
validation
func Auth(c *gophercloud.ProviderClient, opts AuthOptsBuilder) (r GetAuthResult) { h := make(map[string]string) if opts != nil { headers, err := opts.ToAuthOptsMap() if err != nil { r.Err = err return } for k, v := range headers { h[k] = v } } resp, err := c.Request("GET", getURL(c), &gophercl...
go
{ "resource": "" }
q174011
Collaborations
validation
func (c *Client) Collaborations() ([]Collaboration, error) { var cl []Collaboration _, err := c.MakeApiRequest("GET", "/1.0/user/collaborations", nil, &cl) if err != nil { return nil, err } return cl, err }
go
{ "resource": "" }
q174012
Collaboration
validation
func (c *Client) Collaboration(identifier string) (*Collaboration, error) { col := new(Collaboration) _, err := c.MakeApiRequest("GET", "/1.0/user/collaborations/"+identifier, nil, col) if err != nil { return nil, err } return col, err }
go
{ "resource": "" }
q174013
DatabaseSnapshots
validation
func (c *Client) DatabaseSnapshots() ([]DatabaseSnapshot, error) { var database_snapshot []DatabaseSnapshot _, err := c.MakeApiRequest("GET", "/1.0/database_snapshots", nil, &database_snapshot) if err != nil { return nil, err } return database_snapshot, err }
go
{ "resource": "" }
q174014
DatabaseSnapshot
validation
func (c *Client) DatabaseSnapshot(identifier string) (*DatabaseSnapshot, error) { database_snapshot := new(DatabaseSnapshot) _, err := c.MakeApiRequest("GET", "/1.0/database_snapshots/"+identifier, nil, database_snapshot) if err != nil { return nil, err } return database_snapshot, err }
go
{ "resource": "" }
q174015
Scan
validation
func (d PingScanner) Scan() (aliveIPs []string, err error) { var hostsInCidr []string if hostsInCidr, err = expandCidrIntoIPs(d.CIDR); err != nil { return nil, err } pingChan := make(chan string, d.NumOfConcurrency) pongChan := make(chan pong, len(hostsInCidr)) doneChan := make(chan []pong) for i := 0; i < d....
go
{ "resource": "" }
q174016
ToFile
validation
func ToFile(src, dest string, options FileOptions) error { u, err := url.Parse(src) if err != nil { return errors.Wrap(err, "invalid src URL") } targetDir := filepath.Dir(dest) if err = createDir(targetDir, options.Mkdirs == nil || *options.Mkdirs); err != nil { return err } targetName := filepath.Base(des...
go
{ "resource": "" }
q174017
ToWriter
validation
func ToWriter(src string, w io.Writer, options Options) error { u, err := url.Parse(src) if err != nil { return errors.Wrap(err, "invalid src URL") } return FromURL(u, w, options) }
go
{ "resource": "" }
q174018
FromURL
validation
func FromURL(src *url.URL, w io.Writer, options Options) error { httpClient := getHTTPClient(options) var ( err error resp *http.Response ) downloader := func() error { resp, err = httpClient.Get(src.String()) if err != nil { return &retriableError{errors.Wrap(err, "Temporary download error")} } if ...
go
{ "resource": "" }
q174019
ForPeriod
validation
func (totp *TOTP) ForPeriod(period int64) int32 { data := int_to_bytestring(period) hmacHash := hmac.New(sha1.New, totp.key) hmacHash.Write(data) digest := hmacHash.Sum(nil) offset := int(digest[19] & 0xf) code := int32(digest[offset]&0x7f)<<24 | int32(digest[offset+1]&0xff)<<16 | int32(digest[offset+2]&0xff...
go
{ "resource": "" }
q174020
QRCodeData
validation
func (totp *TOTP) QRCodeData(label string) string { // We need to URL Escape the label, but at the same time, spaces come through // as +'s, so we need to reverse that encoding... label = url.QueryEscape(label) label = strings.Replace(label, "+", " ", -1) return fmt.Sprintf("otpauth://totp/%v?secret=%v&Digits=%v&P...
go
{ "resource": "" }
q174021
RandomSecret
validation
func RandomSecret(length int, rnd *rand.Rand) string { if 0 <= length { length = 10 } secret := make([]byte, length) for i, _ := range secret { secret[i] = byte(rnd.Int31() % 256) } return base32.StdEncoding.EncodeToString(secret) }
go
{ "resource": "" }
q174022
DefaultPeerConfig
validation
func DefaultPeerConfig() *PeerConfig { return &PeerConfig{ AuthEnc: true, HandshakeTimeout: 2 * time.Second, DialTimeout: 3 * time.Second, MConfig: DefaultMConnConfig(), Fuzz: false, FuzzConfig: DefaultFuzzConnConfig(), } }
go
{ "resource": "" }
q174023
PubKey
validation
func (p *Peer) PubKey() crypto.PubKeyEd25519 { if p.config.AuthEnc { return p.conn.(*SecretConnection).RemotePubKey() } if p.NodeInfo == nil { panic("Attempt to get peer's PubKey before calling Handshake") } return p.PubKey() }
go
{ "resource": "" }
q174024
OnStart
validation
func (p *Peer) OnStart() error { p.BaseService.OnStart() _, err := p.mconn.Start() return err }
go
{ "resource": "" }
q174025
Send
validation
func (p *Peer) Send(chID byte, msg interface{}) bool { if !p.IsRunning() { // see Switch#Broadcast, where we fetch the list of peers and loop over // them - while we're looping, one peer may be removed and stopped. return false } return p.mconn.Send(chID, msg) }
go
{ "resource": "" }
q174026
WriteTo
validation
func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { var n_ int wire.WriteString(p.Key, w, &n_, &err) n += int64(n_) return }
go
{ "resource": "" }
q174027
Equals
validation
func (p *Peer) Equals(other *Peer) bool { return p.Key == other.Key }
go
{ "resource": "" }
q174028
FuzzConnAfter
validation
func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn { return FuzzConnAfterFromConfig(conn, d, DefaultFuzzConnConfig()) }
go
{ "resource": "" }
q174029
NewMConnectionWithConfig
validation
func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnConfig) *MConnection { mconn := &MConnection{ conn: conn, bufReader: bufio.NewReaderSize(conn, minReadBufferSize), bufWriter: bufio.NewWriterSize(conn, minWriteBufferSi...
go
{ "resource": "" }
q174030
_recover
validation
func (c *MConnection) _recover() { if r := recover(); r != nil { stack := debug.Stack() err := cmn.StackError{r, stack} c.stopForError(err) } }
go
{ "resource": "" }
q174031
Send
validation
func (c *MConnection) Send(chID byte, msg interface{}) bool { if !c.IsRunning() { return false } log.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { log.Error(cmn.Fmt("Cannot send bytes, unknown...
go
{ "resource": "" }
q174032
TrySend
validation
func (c *MConnection) TrySend(chID byte, msg interface{}) bool { if !c.IsRunning() { return false } log.Debug("TrySend", "channel", chID, "conn", c, "msg", msg) // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) return ...
go
{ "resource": "" }
q174033
CanSend
validation
func (c *MConnection) CanSend(chID byte) bool { if !c.IsRunning() { return false } channel, ok := c.channelsIdx[chID] if !ok { log.Error(cmn.Fmt("Unknown channel %X", chID)) return false } return channel.canSend() }
go
{ "resource": "" }
q174034
sendRoutine
validation
func (c *MConnection) sendRoutine() { defer c._recover() FOR_LOOP: for { var n int var err error select { case <-c.flushTimer.Ch: // NOTE: flushTimer.Set() must be called every time // something is written to .bufWriter. c.flush() case <-c.chStatsTimer.Ch: for _, channel := range c.channels { ...
go
{ "resource": "" }
q174035
sendSomeMsgPackets
validation
func (c *MConnection) sendSomeMsgPackets() bool { // Block until .sendMonitor says we can write. // Once we're ready we send more than we asked for, // but amortized it should even out. c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.config.SendRate), true) // Now send some msgPackets. for i := 0;...
go
{ "resource": "" }
q174036
sendMsgPacket
validation
func (c *MConnection) sendMsgPacket() bool { // Choose a channel to create a msgPacket from. // The chosen channel will be the one whose recentlySent/priority is the least. var leastRatio float32 = math.MaxFloat32 var leastChannel *Channel for _, channel := range c.channels { // If nothing to send, skip this cha...
go
{ "resource": "" }
q174037
nextMsgPacket
validation
func (ch *Channel) nextMsgPacket() msgPacket { packet := msgPacket{} packet.ChannelID = byte(ch.id) packet.Bytes = ch.sending[:cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending))] if len(ch.sending) <= maxMsgPacketPayloadSize { packet.EOF = byte(0x01) ch.sending = nil atomic.AddInt32(&ch.sendQueueSize, -1) /...
go
{ "resource": "" }
q174038
writeMsgPacketTo
validation
func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) { packet := ch.nextMsgPacket() log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) wire.WriteByte(packetTypeMsg, w, &n, &err) wire.WriteBinary(packet, w, &n, &err) if err == nil { ch.recentlySent += int64(n) } return }
go
{ "resource": "" }
q174039
recvMsgPacket
validation
func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) { return nil, wire.ErrBinaryReadOverflow } ch.recving = append(ch.recving, packet.Bytes...) if packet.EOF == b...
go
{ "resource": "" }
q174040
hash24
validation
func hash24(input []byte) (res *[24]byte) { hasher := ripemd160.New() hasher.Write(input) // does not error resSlice := hasher.Sum(nil) res = new([24]byte) copy(res[:], resSlice) return }
go
{ "resource": "" }
q174041
incrNonce
validation
func incrNonce(nonce *[24]byte) { for i := 23; 0 <= i; i-- { nonce[i] += 1 if nonce[i] != 0 { return } } }
go
{ "resource": "" }
q174042
List
validation
func (ps *PeerSet) List() []*Peer { ps.mtx.Lock() defer ps.mtx.Unlock() return ps.list }
go
{ "resource": "" }
q174043
listenRoutine
validation
func (l *DefaultListener) listenRoutine() { for { conn, err := l.listener.Accept() if !l.IsRunning() { break // Go to cleanup } // listener wasn't stopped, // yet we encountered an error. if err != nil { PanicCrisis(err) } l.connections <- conn } // Cleanup close(l.connections) for _ = ra...
go
{ "resource": "" }
q174044
NewAddrBook
validation
func NewAddrBook(filePath string, routabilityStrict bool) *AddrBook { am := &AddrBook{ rand: rand.New(rand.NewSource(time.Now().UnixNano())), ourAddrs: make(map[string]*NetAddress), addrLookup: make(map[string]*knownAddress), filePath: filePath, routabilityStrict: routab...
go
{ "resource": "" }
q174045
OnStart
validation
func (a *AddrBook) OnStart() error { a.BaseService.OnStart() a.loadFromFile(a.filePath) a.wg.Add(1) go a.saveRoutine() return nil }
go
{ "resource": "" }
q174046
RemoveAddress
validation
func (a *AddrBook) RemoveAddress(addr *NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.addrLookup[addr.String()] if ka == nil { return } log.Info("Remove address from book", "addr", addr) a.removeFromAllBuckets(ka) }
go
{ "resource": "" }
q174047
loadFromFile
validation
func (a *AddrBook) loadFromFile(filePath string) bool { // If doesn't exist, do nothing. _, err := os.Stat(filePath) if os.IsNotExist(err) { return false } // Load addrBookJSON{} r, err := os.Open(filePath) if err != nil { PanicCrisis(Fmt("Error opening file %s: %v", filePath, err)) } defer r.Close() aJS...
go
{ "resource": "" }
q174048
Save
validation
func (a *AddrBook) Save() { log.Info("Saving AddrBook to file", "size", a.Size()) a.saveToFile(a.filePath) }
go
{ "resource": "" }
q174049
addToOldBucket
validation
func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { // Sanity check if ka.isNew() { log.Warn(Fmt("Cannot add new address to old bucket: %v", ka)) return false } if len(ka.Buckets) != 0 { log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka)) return false } add...
go
{ "resource": "" }
q174050
expireNew
validation
func (a *AddrBook) expireNew(bucketIdx int) { for addrStr, ka := range a.addrNew[bucketIdx] { // If an entry is bad, throw it away if ka.isBad() { log.Notice(Fmt("expiring bad address %v", addrStr)) a.removeFromBucket(ka, bucketTypeNew, bucketIdx) return } } // If we haven't thrown out a bad entry, t...
go
{ "resource": "" }
q174051
DialSeeds
validation
func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error { netAddrs, err := NewNetAddressStrings(seeds) if err != nil { return err } if addrBook != nil { // add seeds to `addrBook` ourAddrS := sw.nodeInfo.ListenAddr ourAddr, _ := NewNetAddressString(ourAddrS) for _, netAddr := range netAddr...
go
{ "resource": "" }
q174052
NewNetAddressStrings
validation
func NewNetAddressStrings(addrs []string) ([]*NetAddress, error) { netAddrs := make([]*NetAddress, len(addrs)) for i, addr := range addrs { netAddr, err := NewNetAddressString(addr) if err != nil { return nil, errors.New(cmn.Fmt("Error in address %s: %v", addr, err)) } netAddrs[i] = netAddr } return netA...
go
{ "resource": "" }
q174053
NewNetAddressIPPort
validation
func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { na := &NetAddress{ IP: ip, Port: port, str: net.JoinHostPort( ip.String(), strconv.FormatUint(uint64(port), 10), ), } return na }
go
{ "resource": "" }
q174054
Equals
validation
func (na *NetAddress) Equals(other interface{}) bool { if o, ok := other.(*NetAddress); ok { return na.String() == o.String() } return false }
go
{ "resource": "" }
q174055
Dial
validation
func (na *NetAddress) Dial() (net.Conn, error) { conn, err := net.Dial("tcp", na.String()) if err != nil { return nil, err } return conn, nil }
go
{ "resource": "" }
q174056
Valid
validation
func (na *NetAddress) Valid() bool { return na.IP != nil && !(na.IP.IsUnspecified() || na.RFC3849() || na.IP.Equal(net.IPv4bcast)) }
go
{ "resource": "" }
q174057
ReachabilityTo
validation
func (na *NetAddress) ReachabilityTo(o *NetAddress) int { const ( Unreachable = 0 Default = iota Teredo Ipv6_weak Ipv4 Ipv6_strong Private ) if !na.Routable() { return Unreachable } else if na.RFC4380() { if !o.Routable() { return Default } else if o.RFC4380() { return Teredo } else ...
go
{ "resource": "" }
q174058
NewPEXReactor
validation
func NewPEXReactor(b *AddrBook) *PEXReactor { r := &PEXReactor{ book: b, ensurePeersPeriod: defaultEnsurePeersPeriod, msgCountByPeer: cmn.NewCMap(), maxMsgCountByPeer: defaultMaxMsgCountByPeer, } r.BaseReactor = *NewBaseReactor(log, "PEXReactor", r) return r }
go
{ "resource": "" }
q174059
OnStart
validation
func (r *PEXReactor) OnStart() error { r.BaseReactor.OnStart() r.book.Start() go r.ensurePeersRoutine() go r.flushMsgCountByPeer() return nil }
go
{ "resource": "" }
q174060
Receive
validation
func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { srcAddr := src.Connection().RemoteAddress srcAddrStr := srcAddr.String() r.IncrementMsgCountForPeer(srcAddrStr) if r.ReachedMaxMsgCountForPeer(srcAddrStr) { log.Warn("Maximum number of messages reached for peer", "peer", srcAddrStr) // TODO ...
go
{ "resource": "" }
q174061
RequestPEX
validation
func (r *PEXReactor) RequestPEX(p *Peer) { p.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}}) }
go
{ "resource": "" }
q174062
SendAddrs
validation
func (r *PEXReactor) SendAddrs(p *Peer, addrs []*NetAddress) { p.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) }
go
{ "resource": "" }
q174063
IncrementMsgCountForPeer
validation
func (r *PEXReactor) IncrementMsgCountForPeer(addr string) { var count uint16 countI := r.msgCountByPeer.Get(addr) if countI != nil { count = countI.(uint16) } count++ r.msgCountByPeer.Set(addr, count) }
go
{ "resource": "" }
q174064
DecodeMessage
validation
func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) { msgType = bz[0] n := new(int) r := bytes.NewReader(bz) msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage return }
go
{ "resource": "" }
q174065
NewReader
validation
func NewReader(r io.Reader) *Reader { return &Reader{ Reader: csv.NewReader(r), } }
go
{ "resource": "" }
q174066
LogOnPanic
validation
func LogOnPanic(id int64, err interface{}, stacktrace []string, _ *http.Request) { logMutex.Lock() defer logMutex.Unlock() log.Printf("panic=%016x message=%v\n", id, err) for _, line := range stacktrace { log.Printf("panic=%016x %s", id, line) } }
go
{ "resource": "" }
q174067
Wrap
validation
func Wrap(h http.Handler, onPanic PanicHandler) http.Handler { return &recoveryHandler{h: h, p: onPanic} }
go
{ "resource": "" }
q174068
Start
validation
func (al *LoggingHandler) Start() { go func() { for s := range al.buffer { fmt.Fprint(al.w, s) } close(al.quit) }() }
go
{ "resource": "" }
q174069
New
validation
func New(h http.Handler, onPanic recovery.PanicHandler) Service { l := logging.Wrap( recovery.Wrap( debug.Wrap( metrics.Wrap( h, ), ), onPanic, ), os.Stdout, ) l.Start() return Service{h: l} }
go
{ "resource": "" }
q174070
Wrap
validation
func (v *X509NameVerifier) Wrap(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { dn := r.Header.Get(v.HeaderName) var name *pkix.Name if dn != "" { name = parseDN(dn) } if name != nil && v.CheckCertificate(name) { h.ServeHTTP(w, r) } else if v.In...
go
{ "resource": "" }
q174071
GetString
validation
func (c HubConfig) GetString(key string, defval string) string { val, ok := c[key] if ok { s, ok := val.(string) if ok && len(s) > 0 { return s } // TODO only primitive types return fmt.Sprintf("%s", val) } return defval }
go
{ "resource": "" }
q174072
GetInt
validation
func (c HubConfig) GetInt(key string, defval int) int { val, ok := c[key] if ok { i, ok := val.(int) if ok { return i } s := c.GetString(key, "") if len(s) > 0 { i, err := strconv.Atoi(s) if err != nil { // TODO handling error on app level return defval } return i } } return defva...
go
{ "resource": "" }
q174073
RegisterDriver
validation
func RegisterDriver(d Driver, knownNames ...string) { for _, k := range knownNames { drivers[strings.ToLower(k)] = d } log.Info("registered pubsub driver: %v", knownNames) }
go
{ "resource": "" }
q174074
Open
validation
func Open(URL ...string) (pubsub.Hub, error) { redisURL := getRedisURL(URL...) conn, err := redisurl.ConnectToURL(redisURL) if err != nil { return nil, err } return &hub{ conn: conn, redisURL: redisURL, subs: make(map[*sub]struct{}), }, nil }
go
{ "resource": "" }
q174075
SendEvents
validation
func SendEvents(w http.ResponseWriter, r *http.Request, channels []string) { // make sure that the writer supports flushing flusher, ok := w.(http.Flusher) if !ok { log.Error("current response %T does not implement http.Flusher, plase check your middlewares that wraps response", w) http.Error(w, "streaming unsu...
go
{ "resource": "" }
q174076
Unmarshal
validation
func Unmarshal(data []byte) (interface{}, error) { var msg map[string]interface{} err := json.Unmarshal(data, &msg) if err != nil { log.Errorf("json.Unmarshal failed: %+v", err) return nil, err } return msg, nil }
go
{ "resource": "" }
q174077
Publish
validation
func (hub *hub) Publish(channels []string, msg interface{}) { for _, name := range channels { var cn = hub.getChannel(name) cn.Publish(msg) } }
go
{ "resource": "" }
q174078
Subscribe
validation
func (hub *hub) Subscribe(channels []string) (Channel, error) { var chans []*channel for _, name := range channels { chans = append(chans, hub.getChannel(name)) } var sub = makeSub(chans) for _, cn := range chans { cn.Subscribe(sub) } return sub, nil }
go
{ "resource": "" }
q174079
getChannel
validation
func (hub *hub) getChannel(name string) *channel { hub.Lock() defer hub.Unlock() cn, ok := hub.channels[name] if ok { return cn } cn = makeChannel(hub, name) hub.channels[name] = cn go cn.start() return cn }
go
{ "resource": "" }
q174080
remove
validation
func (hub *hub) remove(cn *channel) { hub.Lock() defer hub.Unlock() cn, ok := hub.channels[cn.name] if !ok { return } delete(hub.channels, cn.name) return }
go
{ "resource": "" }
q174081
Open
validation
func Open(URL ...string) (pubsub.Hub, error) { if len(URL) == 0 { URL = []string{nats.DefaultURL} } log.Info("connecting to nats hub: %v", URL) conn, err := nats.Connect(URL[0]) if err != nil { return nil, err } return &hub{ conn: conn, subs: make(map[*sub]struct{}), }, nil }
go
{ "resource": "" }
q174082
Publish
validation
func Publish(channels []string, msg interface{}) error { if hubInstance == nil { return errorNohub } log.Debug("publish to %v", channels) hubInstance.Publish(channels, msg) return nil }
go
{ "resource": "" }
q174083
Subscribe
validation
func Subscribe(channels []string) (Channel, error) { if hubInstance == nil { return nil, errorNohub } r, err := hubInstance.Subscribe(channels) if err != nil { log.Errorf("pubsub subscribe failed: %+v", err) return nil, err } log.Debug("subscibe to %v", channels) return r, nil }
go
{ "resource": "" }
q174084
MakeHub
validation
func MakeHub(config HubConfig) (Hub, error) { if config == nil { return NewHub(), nil } driverName := getDriverName(config) if len(driverName) == 0 { return nil, fmt.Errorf("driver name is not specified") } d, ok := drivers[driverName] if ok { h, err := d.Create(config) if err != nil { log.Errorf("un...
go
{ "resource": "" }
q174085
Fib
validation
func Fib() func() time.Duration { a, b := 0, 1 return func() time.Duration { a, b = b, a+b return time.Duration(a*10) * time.Millisecond } }
go
{ "resource": "" }
q174086
roundIndex
validation
func roundIndex(start, max int) []int { if start < 0 { start = 0 } result := make([]int, max) for i := 0; i < max; i++ { if start+i < max { result[i] = start + i } else { result[i] = int(math.Abs(float64(max - (start + i)))) } } return result }
go
{ "resource": "" }
q174087
Dir
validation
func Dir() (string, error) { currentUser, err := user.Current() if err != nil { return "", err } if currentUser.HomeDir == "" { return "", errors.New("cannot find user-specific home dir") } return currentUser.HomeDir, nil }
go
{ "resource": "" }
q174088
Ask
validation
func (s *Session) Ask(question string) (string, error) { s.mu.Lock() defer s.mu.Unlock() s.Values.Set("input", question) // Clear previous json, just in case s.clear() // Prepare the request. req, err := http.NewRequest("GET", apiURL+s.Values.Encode(), nil) if err != nil { return "", err } // Headers. req...
go
{ "resource": "" }
q174089
InteractionCount
validation
func (s *Session) InteractionCount() int { s.mu.Lock() defer s.mu.Unlock() if v, ok := s.Decoded["interaction_count"].(string); ok { if count, err := strconv.Atoi(v); err == nil { return count } } return -1 }
go
{ "resource": "" }
q174090
TimeElapsed
validation
func (s *Session) TimeElapsed() time.Duration { s.mu.Lock() defer s.mu.Unlock() if v, ok := s.Decoded["time_elapsed"].(string); ok { if dur, err := time.ParseDuration(v + "s"); err == nil { return dur } } return time.Second * -1 }
go
{ "resource": "" }
q174091
History
validation
func (s *Session) History() QAPairs { s.mu.Lock() defer s.mu.Unlock() var qa []QAPair for i := 1; ; i++ { if v, ok := s.Decoded[fmt.Sprintf("interaction_%d_other", i)].(string); ok && v != "" { qa = append([]QAPair{{s.Decoded[fmt.Sprintf("interaction_%d", i)].(string), s.Decoded[fmt.Sprintf("interaction_%d...
go
{ "resource": "" }
q174092
Bool
validation
func (f Flags) Bool(name string) bool { return f.C.Bool(name) }
go
{ "resource": "" }
q174093
String
validation
func (f Flags) String(name string) string { return f.C.String(name) }
go
{ "resource": "" }
q174094
Fail
validation
func (t *T) Fail() { t.mu.Lock() defer t.mu.Unlock() t.failed = true }
go
{ "resource": "" }
q174095
Failed
validation
func (t *T) Failed() bool { t.mu.Lock() defer t.mu.Unlock() return t.failed }
go
{ "resource": "" }
q174096
Logf
validation
func (t *T) Logf(format string, args ...interface{}) { fmt.Printf(format, args...) }
go
{ "resource": "" }
q174097
Error
validation
func (t *T) Error(args ...interface{}) { fmt.Fprintln(os.Stderr, args...) t.Fail() }
go
{ "resource": "" }
q174098
Errorf
validation
func (t *T) Errorf(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) t.Fail() }
go
{ "resource": "" }
q174099
Init
validation
func (c *Client) Init(root, auth string, api Api) { if api == nil { api = new(f) } c.api = api c.Url = root c.Auth = auth }
go
{ "resource": "" }