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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
gopherjs/vecty | dom.go | AddStylesheet | func AddStylesheet(url string) {
link := global.Get("document").Call("createElement", "link")
link.Set("rel", "stylesheet")
link.Set("href", url)
global.Get("document").Get("head").Call("appendChild", link)
} | go | func AddStylesheet(url string) {
link := global.Get("document").Call("createElement", "link")
link.Set("rel", "stylesheet")
link.Set("href", url)
global.Get("document").Get("head").Call("appendChild", link)
} | [
"func",
"AddStylesheet",
"(",
"url",
"string",
")",
"{",
"link",
":=",
"global",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"Call",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"link",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"lin... | // AddStylesheet adds an external stylesheet to the document. | [
"AddStylesheet",
"adds",
"an",
"external",
"stylesheet",
"to",
"the",
"document",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/dom.go#L1198-L1203 | train |
gopherjs/vecty | markup.go | Data | func Data(key, value string) Applyer {
return markupFunc(func(h *HTML) {
if h.dataset == nil {
h.dataset = make(map[string]string)
}
h.dataset[key] = value
})
} | go | func Data(key, value string) Applyer {
return markupFunc(func(h *HTML) {
if h.dataset == nil {
h.dataset = make(map[string]string)
}
h.dataset[key] = value
})
} | [
"func",
"Data",
"(",
"key",
",",
"value",
"string",
")",
"Applyer",
"{",
"return",
"markupFunc",
"(",
"func",
"(",
"h",
"*",
"HTML",
")",
"{",
"if",
"h",
".",
"dataset",
"==",
"nil",
"{",
"h",
".",
"dataset",
"=",
"make",
"(",
"map",
"[",
"string... | // Data returns an Applyer which applies the given data attribute. | [
"Data",
"returns",
"an",
"Applyer",
"which",
"applies",
"the",
"given",
"data",
"attribute",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L140-L147 | train |
gopherjs/vecty | markup.go | Class | func Class(class ...string) Applyer {
mustValidateClassNames(class)
return markupFunc(func(h *HTML) {
if h.classes == nil {
h.classes = make(map[string]struct{})
}
for _, name := range class {
h.classes[name] = struct{}{}
}
})
} | go | func Class(class ...string) Applyer {
mustValidateClassNames(class)
return markupFunc(func(h *HTML) {
if h.classes == nil {
h.classes = make(map[string]struct{})
}
for _, name := range class {
h.classes[name] = struct{}{}
}
})
} | [
"func",
"Class",
"(",
"class",
"...",
"string",
")",
"Applyer",
"{",
"mustValidateClassNames",
"(",
"class",
")",
"\n",
"return",
"markupFunc",
"(",
"func",
"(",
"h",
"*",
"HTML",
")",
"{",
"if",
"h",
".",
"classes",
"==",
"nil",
"{",
"h",
".",
"clas... | // Class returns an Applyer which applies the provided classes. Subsequent
// calls to this function will append additional classes. To toggle classes,
// use ClassMap instead. Each class name must be passed as a separate argument. | [
"Class",
"returns",
"an",
"Applyer",
"which",
"applies",
"the",
"provided",
"classes",
".",
"Subsequent",
"calls",
"to",
"this",
"function",
"will",
"append",
"additional",
"classes",
".",
"To",
"toggle",
"classes",
"use",
"ClassMap",
"instead",
".",
"Each",
"... | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L152-L162 | train |
gopherjs/vecty | markup.go | mustValidateClassNames | func mustValidateClassNames(class []string) {
for _, name := range class {
if containsSpace(name) {
panic(`vecty: invalid argument to vecty.Class "` + name + `" (string may not contain spaces)`)
}
}
} | go | func mustValidateClassNames(class []string) {
for _, name := range class {
if containsSpace(name) {
panic(`vecty: invalid argument to vecty.Class "` + name + `" (string may not contain spaces)`)
}
}
} | [
"func",
"mustValidateClassNames",
"(",
"class",
"[",
"]",
"string",
")",
"{",
"for",
"_",
",",
"name",
":=",
"range",
"class",
"{",
"if",
"containsSpace",
"(",
"name",
")",
"{",
"panic",
"(",
"`vecty: invalid argument to vecty.Class \"`",
"+",
"name",
"+",
"... | // mustValidateClassNames ensures no class names have spaces
// and panics with clear instructions on how to fix this user error. | [
"mustValidateClassNames",
"ensures",
"no",
"class",
"names",
"have",
"spaces",
"and",
"panics",
"with",
"clear",
"instructions",
"on",
"how",
"to",
"fix",
"this",
"user",
"error",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L166-L172 | train |
gopherjs/vecty | markup.go | containsSpace | func containsSpace(s string) bool {
for _, c := range s {
if c == ' ' {
return true
}
}
return false
} | go | func containsSpace(s string) bool {
for _, c := range s {
if c == ' ' {
return true
}
}
return false
} | [
"func",
"containsSpace",
"(",
"s",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"s",
"{",
"if",
"c",
"==",
"' '",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // containsSpace reports whether s contains a space character. | [
"containsSpace",
"reports",
"whether",
"s",
"contains",
"a",
"space",
"character",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L175-L182 | train |
gopherjs/vecty | markup.go | If | func If(cond bool, children ...ComponentOrHTML) MarkupOrChild {
if cond {
return List(children)
}
return nil
} | go | func If(cond bool, children ...ComponentOrHTML) MarkupOrChild {
if cond {
return List(children)
}
return nil
} | [
"func",
"If",
"(",
"cond",
"bool",
",",
"children",
"...",
"ComponentOrHTML",
")",
"MarkupOrChild",
"{",
"if",
"cond",
"{",
"return",
"List",
"(",
"children",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // If returns nil if cond is false, otherwise it returns the given children. | [
"If",
"returns",
"nil",
"if",
"cond",
"is",
"false",
"otherwise",
"it",
"returns",
"the",
"given",
"children",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L234-L239 | train |
gopherjs/vecty | markup.go | MarkupIf | func MarkupIf(cond bool, markup ...Applyer) Applyer {
if cond {
return Markup(markup...)
}
return nil
} | go | func MarkupIf(cond bool, markup ...Applyer) Applyer {
if cond {
return Markup(markup...)
}
return nil
} | [
"func",
"MarkupIf",
"(",
"cond",
"bool",
",",
"markup",
"...",
"Applyer",
")",
"Applyer",
"{",
"if",
"cond",
"{",
"return",
"Markup",
"(",
"markup",
"...",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MarkupIf returns nil if cond is false, otherwise it returns the given markup. | [
"MarkupIf",
"returns",
"nil",
"if",
"cond",
"is",
"false",
"otherwise",
"it",
"returns",
"the",
"given",
"markup",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/markup.go#L242-L247 | train |
gopherjs/vecty | example/todomvc/dispatcher/dispatcher.go | Register | func Register(callback func(action interface{})) ID {
idCounter++
id := idCounter
callbacks[id] = callback
return id
} | go | func Register(callback func(action interface{})) ID {
idCounter++
id := idCounter
callbacks[id] = callback
return id
} | [
"func",
"Register",
"(",
"callback",
"func",
"(",
"action",
"interface",
"{",
"}",
")",
")",
"ID",
"{",
"idCounter",
"++",
"\n",
"id",
":=",
"idCounter",
"\n",
"callbacks",
"[",
"id",
"]",
"=",
"callback",
"\n",
"return",
"id",
"\n",
"}"
] | // Register registers the callback to handle dispatched actions, the returned
// ID may be used to unregister the callback later. | [
"Register",
"registers",
"the",
"callback",
"to",
"handle",
"dispatched",
"actions",
"the",
"returned",
"ID",
"may",
"be",
"used",
"to",
"unregister",
"the",
"callback",
"later",
"."
] | d00da0c86b426642cf5acc29133d33491a711209 | https://github.com/gopherjs/vecty/blob/d00da0c86b426642cf5acc29133d33491a711209/example/todomvc/dispatcher/dispatcher.go#L18-L23 | train |
dghubble/go-twitter | twitter/twitter.go | Bool | func Bool(v bool) *bool {
ptr := new(bool)
*ptr = v
return ptr
} | go | func Bool(v bool) *bool {
ptr := new(bool)
*ptr = v
return ptr
} | [
"func",
"Bool",
"(",
"v",
"bool",
")",
"*",
"bool",
"{",
"ptr",
":=",
"new",
"(",
"bool",
")",
"\n",
"*",
"ptr",
"=",
"v",
"\n",
"return",
"ptr",
"\n",
"}"
] | // Bool returns a new pointer to the given bool value. | [
"Bool",
"returns",
"a",
"new",
"pointer",
"to",
"the",
"given",
"bool",
"value",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/twitter.go#L54-L58 | train |
dghubble/go-twitter | twitter/twitter.go | Float | func Float(v float64) *float64 {
ptr := new(float64)
*ptr = v
return ptr
} | go | func Float(v float64) *float64 {
ptr := new(float64)
*ptr = v
return ptr
} | [
"func",
"Float",
"(",
"v",
"float64",
")",
"*",
"float64",
"{",
"ptr",
":=",
"new",
"(",
"float64",
")",
"\n",
"*",
"ptr",
"=",
"v",
"\n",
"return",
"ptr",
"\n",
"}"
] | // Float returns a new pointer to the given float64 value. | [
"Float",
"returns",
"a",
"new",
"pointer",
"to",
"the",
"given",
"float64",
"value",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/twitter.go#L61-L65 | train |
dghubble/go-twitter | twitter/demux.go | NewSwitchDemux | func NewSwitchDemux() SwitchDemux {
return SwitchDemux{
All: func(message interface{}) {},
Tweet: func(tweet *Tweet) {},
DM: func(dm *DirectMessage) {},
StatusDeletion: func(deletion *StatusDeletion) {},
LocationDeletion: func(LocationDeletion *LocationDeletion) {},
StreamLimit: func(limit *StreamLimit) {},
StatusWithheld: func(statusWithheld *StatusWithheld) {},
UserWithheld: func(userWithheld *UserWithheld) {},
StreamDisconnect: func(disconnect *StreamDisconnect) {},
Warning: func(warning *StallWarning) {},
FriendsList: func(friendsList *FriendsList) {},
Event: func(event *Event) {},
Other: func(message interface{}) {},
}
} | go | func NewSwitchDemux() SwitchDemux {
return SwitchDemux{
All: func(message interface{}) {},
Tweet: func(tweet *Tweet) {},
DM: func(dm *DirectMessage) {},
StatusDeletion: func(deletion *StatusDeletion) {},
LocationDeletion: func(LocationDeletion *LocationDeletion) {},
StreamLimit: func(limit *StreamLimit) {},
StatusWithheld: func(statusWithheld *StatusWithheld) {},
UserWithheld: func(userWithheld *UserWithheld) {},
StreamDisconnect: func(disconnect *StreamDisconnect) {},
Warning: func(warning *StallWarning) {},
FriendsList: func(friendsList *FriendsList) {},
Event: func(event *Event) {},
Other: func(message interface{}) {},
}
} | [
"func",
"NewSwitchDemux",
"(",
")",
"SwitchDemux",
"{",
"return",
"SwitchDemux",
"{",
"All",
":",
"func",
"(",
"message",
"interface",
"{",
"}",
")",
"{",
"}",
",",
"Tweet",
":",
"func",
"(",
"tweet",
"*",
"Tweet",
")",
"{",
"}",
",",
"DM",
":",
"f... | // NewSwitchDemux returns a new SwitchMux which has NoOp handler functions. | [
"NewSwitchDemux",
"returns",
"a",
"new",
"SwitchMux",
"which",
"has",
"NoOp",
"handler",
"functions",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/demux.go#L30-L46 | train |
dghubble/go-twitter | twitter/demux.go | Handle | func (d SwitchDemux) Handle(message interface{}) {
d.All(message)
switch msg := message.(type) {
case *Tweet:
d.Tweet(msg)
case *DirectMessage:
d.DM(msg)
case *StatusDeletion:
d.StatusDeletion(msg)
case *LocationDeletion:
d.LocationDeletion(msg)
case *StreamLimit:
d.StreamLimit(msg)
case *StatusWithheld:
d.StatusWithheld(msg)
case *UserWithheld:
d.UserWithheld(msg)
case *StreamDisconnect:
d.StreamDisconnect(msg)
case *StallWarning:
d.Warning(msg)
case *FriendsList:
d.FriendsList(msg)
case *Event:
d.Event(msg)
default:
d.Other(msg)
}
} | go | func (d SwitchDemux) Handle(message interface{}) {
d.All(message)
switch msg := message.(type) {
case *Tweet:
d.Tweet(msg)
case *DirectMessage:
d.DM(msg)
case *StatusDeletion:
d.StatusDeletion(msg)
case *LocationDeletion:
d.LocationDeletion(msg)
case *StreamLimit:
d.StreamLimit(msg)
case *StatusWithheld:
d.StatusWithheld(msg)
case *UserWithheld:
d.UserWithheld(msg)
case *StreamDisconnect:
d.StreamDisconnect(msg)
case *StallWarning:
d.Warning(msg)
case *FriendsList:
d.FriendsList(msg)
case *Event:
d.Event(msg)
default:
d.Other(msg)
}
} | [
"func",
"(",
"d",
"SwitchDemux",
")",
"Handle",
"(",
"message",
"interface",
"{",
"}",
")",
"{",
"d",
".",
"All",
"(",
"message",
")",
"\n",
"switch",
"msg",
":=",
"message",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Tweet",
":",
"d",
".",
"Tweet... | // Handle determines the type of a message and calls the corresponding receiver
// function with the typed message. All messages are passed to the All func.
// Messages with unmatched types are passed to the Other func. | [
"Handle",
"determines",
"the",
"type",
"of",
"a",
"message",
"and",
"calls",
"the",
"corresponding",
"receiver",
"function",
"with",
"the",
"typed",
"message",
".",
"All",
"messages",
"are",
"passed",
"to",
"the",
"All",
"func",
".",
"Messages",
"with",
"unm... | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/demux.go#L51-L79 | train |
dghubble/go-twitter | twitter/streams.go | newStreamService | func newStreamService(client *http.Client, sling *sling.Sling) *StreamService {
sling.Set("User-Agent", userAgent)
return &StreamService{
client: client,
public: sling.New().Base(publicStream).Path("statuses/"),
user: sling.New().Base(userStream),
site: sling.New().Base(siteStream),
}
} | go | func newStreamService(client *http.Client, sling *sling.Sling) *StreamService {
sling.Set("User-Agent", userAgent)
return &StreamService{
client: client,
public: sling.New().Base(publicStream).Path("statuses/"),
user: sling.New().Base(userStream),
site: sling.New().Base(siteStream),
}
} | [
"func",
"newStreamService",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"sling",
"*",
"sling",
".",
"Sling",
")",
"*",
"StreamService",
"{",
"sling",
".",
"Set",
"(",
"\"",
"\"",
",",
"userAgent",
")",
"\n",
"return",
"&",
"StreamService",
"{",
"cl... | // newStreamService returns a new StreamService. | [
"newStreamService",
"returns",
"a",
"new",
"StreamService",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L30-L38 | train |
dghubble/go-twitter | twitter/streams.go | Stop | func (s *Stream) Stop() {
close(s.done)
// Scanner does not have a Stop() or take a done channel, so for low volume
// streams Scan() blocks until the next keep-alive. Close the resp.Body to
// escape and stop the stream in a timely fashion.
if s.body != nil {
s.body.Close()
}
// block until the retry goroutine stops
s.group.Wait()
} | go | func (s *Stream) Stop() {
close(s.done)
// Scanner does not have a Stop() or take a done channel, so for low volume
// streams Scan() blocks until the next keep-alive. Close the resp.Body to
// escape and stop the stream in a timely fashion.
if s.body != nil {
s.body.Close()
}
// block until the retry goroutine stops
s.group.Wait()
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Stop",
"(",
")",
"{",
"close",
"(",
"s",
".",
"done",
")",
"\n",
"// Scanner does not have a Stop() or take a done channel, so for low volume",
"// streams Scan() blocks until the next keep-alive. Close the resp.Body to",
"// escape and st... | // Stop signals retry and receiver to stop, closes the Messages channel, and
// blocks until done. | [
"Stop",
"signals",
"retry",
"and",
"receiver",
"to",
"stop",
"closes",
"the",
"Messages",
"channel",
"and",
"blocks",
"until",
"done",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L169-L179 | train |
dghubble/go-twitter | twitter/streams.go | receive | func (s *Stream) receive(body io.Reader) {
reader := newStreamResponseBodyReader(body)
for !stopped(s.done) {
data, err := reader.readNext()
if err != nil {
return
}
if len(data) == 0 {
// empty keep-alive
continue
}
select {
// send messages, data, or errors
case s.Messages <- getMessage(data):
continue
// allow client to Stop(), even if not receiving
case <-s.done:
return
}
}
} | go | func (s *Stream) receive(body io.Reader) {
reader := newStreamResponseBodyReader(body)
for !stopped(s.done) {
data, err := reader.readNext()
if err != nil {
return
}
if len(data) == 0 {
// empty keep-alive
continue
}
select {
// send messages, data, or errors
case s.Messages <- getMessage(data):
continue
// allow client to Stop(), even if not receiving
case <-s.done:
return
}
}
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"receive",
"(",
"body",
"io",
".",
"Reader",
")",
"{",
"reader",
":=",
"newStreamResponseBodyReader",
"(",
"body",
")",
"\n",
"for",
"!",
"stopped",
"(",
"s",
".",
"done",
")",
"{",
"data",
",",
"err",
":=",
"r... | // receive scans a stream response body, JSON decodes tokens to messages, and
// sends messages to the Messages channel. Receiving continues until an EOF,
// scan error, or the done channel is closed. | [
"receive",
"scans",
"a",
"stream",
"response",
"body",
"JSON",
"decodes",
"tokens",
"to",
"messages",
"and",
"sends",
"messages",
"to",
"the",
"Messages",
"channel",
".",
"Receiving",
"continues",
"until",
"an",
"EOF",
"scan",
"error",
"or",
"the",
"done",
"... | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L230-L250 | train |
dghubble/go-twitter | twitter/streams.go | decodeMessage | func decodeMessage(token []byte, data map[string]interface{}) interface{} {
if hasPath(data, "retweet_count") {
tweet := new(Tweet)
json.Unmarshal(token, tweet)
return tweet
} else if hasPath(data, "direct_message") {
notice := new(directMessageNotice)
json.Unmarshal(token, notice)
return notice.DirectMessage
} else if hasPath(data, "delete") {
notice := new(statusDeletionNotice)
json.Unmarshal(token, notice)
return notice.Delete.StatusDeletion
} else if hasPath(data, "scrub_geo") {
notice := new(locationDeletionNotice)
json.Unmarshal(token, notice)
return notice.ScrubGeo
} else if hasPath(data, "limit") {
notice := new(streamLimitNotice)
json.Unmarshal(token, notice)
return notice.Limit
} else if hasPath(data, "status_withheld") {
notice := new(statusWithheldNotice)
json.Unmarshal(token, notice)
return notice.StatusWithheld
} else if hasPath(data, "user_withheld") {
notice := new(userWithheldNotice)
json.Unmarshal(token, notice)
return notice.UserWithheld
} else if hasPath(data, "disconnect") {
notice := new(streamDisconnectNotice)
json.Unmarshal(token, notice)
return notice.StreamDisconnect
} else if hasPath(data, "warning") {
notice := new(stallWarningNotice)
json.Unmarshal(token, notice)
return notice.StallWarning
} else if hasPath(data, "friends") {
friendsList := new(FriendsList)
json.Unmarshal(token, friendsList)
return friendsList
} else if hasPath(data, "event") {
event := new(Event)
json.Unmarshal(token, event)
return event
}
// message type unknown, return the data map[string]interface{}
return data
} | go | func decodeMessage(token []byte, data map[string]interface{}) interface{} {
if hasPath(data, "retweet_count") {
tweet := new(Tweet)
json.Unmarshal(token, tweet)
return tweet
} else if hasPath(data, "direct_message") {
notice := new(directMessageNotice)
json.Unmarshal(token, notice)
return notice.DirectMessage
} else if hasPath(data, "delete") {
notice := new(statusDeletionNotice)
json.Unmarshal(token, notice)
return notice.Delete.StatusDeletion
} else if hasPath(data, "scrub_geo") {
notice := new(locationDeletionNotice)
json.Unmarshal(token, notice)
return notice.ScrubGeo
} else if hasPath(data, "limit") {
notice := new(streamLimitNotice)
json.Unmarshal(token, notice)
return notice.Limit
} else if hasPath(data, "status_withheld") {
notice := new(statusWithheldNotice)
json.Unmarshal(token, notice)
return notice.StatusWithheld
} else if hasPath(data, "user_withheld") {
notice := new(userWithheldNotice)
json.Unmarshal(token, notice)
return notice.UserWithheld
} else if hasPath(data, "disconnect") {
notice := new(streamDisconnectNotice)
json.Unmarshal(token, notice)
return notice.StreamDisconnect
} else if hasPath(data, "warning") {
notice := new(stallWarningNotice)
json.Unmarshal(token, notice)
return notice.StallWarning
} else if hasPath(data, "friends") {
friendsList := new(FriendsList)
json.Unmarshal(token, friendsList)
return friendsList
} else if hasPath(data, "event") {
event := new(Event)
json.Unmarshal(token, event)
return event
}
// message type unknown, return the data map[string]interface{}
return data
} | [
"func",
"decodeMessage",
"(",
"token",
"[",
"]",
"byte",
",",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"if",
"hasPath",
"(",
"data",
",",
"\"",
"\"",
")",
"{",
"tweet",
":=",
"new",
"(",
"Tweet",
... | // decodeMessage determines the message type from known data keys, allocates
// at most one message struct, and JSON decodes the token into the message.
// Returns the message struct or the data map if the message type could not be
// determined. | [
"decodeMessage",
"determines",
"the",
"message",
"type",
"from",
"known",
"data",
"keys",
"allocates",
"at",
"most",
"one",
"message",
"struct",
"and",
"JSON",
"decodes",
"the",
"token",
"into",
"the",
"message",
".",
"Returns",
"the",
"message",
"struct",
"or... | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L269-L317 | train |
dghubble/go-twitter | twitter/streams.go | hasPath | func hasPath(data map[string]interface{}, key string) bool {
_, ok := data[key]
return ok
} | go | func hasPath(data map[string]interface{}, key string) bool {
_, ok := data[key]
return ok
} | [
"func",
"hasPath",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"key",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"data",
"[",
"key",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // hasPath returns true if the map contains the given key, false otherwise. | [
"hasPath",
"returns",
"true",
"if",
"the",
"map",
"contains",
"the",
"given",
"key",
"false",
"otherwise",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/streams.go#L320-L323 | train |
dghubble/go-twitter | twitter/statuses.go | CreatedAtTime | func (t Tweet) CreatedAtTime() (time.Time, error) {
return time.Parse(time.RubyDate, t.CreatedAt)
} | go | func (t Tweet) CreatedAtTime() (time.Time, error) {
return time.Parse(time.RubyDate, t.CreatedAt)
} | [
"func",
"(",
"t",
"Tweet",
")",
"CreatedAtTime",
"(",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"return",
"time",
".",
"Parse",
"(",
"time",
".",
"RubyDate",
",",
"t",
".",
"CreatedAt",
")",
"\n",
"}"
] | // CreatedAtTime returns the time a tweet was created. | [
"CreatedAtTime",
"returns",
"the",
"time",
"a",
"tweet",
"was",
"created",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/statuses.go#L54-L56 | train |
dghubble/go-twitter | twitter/direct_messages.go | newDirectMessageService | func newDirectMessageService(sling *sling.Sling) *DirectMessageService {
return &DirectMessageService{
baseSling: sling.New(),
sling: sling.Path("direct_messages/"),
}
} | go | func newDirectMessageService(sling *sling.Sling) *DirectMessageService {
return &DirectMessageService{
baseSling: sling.New(),
sling: sling.Path("direct_messages/"),
}
} | [
"func",
"newDirectMessageService",
"(",
"sling",
"*",
"sling",
".",
"Sling",
")",
"*",
"DirectMessageService",
"{",
"return",
"&",
"DirectMessageService",
"{",
"baseSling",
":",
"sling",
".",
"New",
"(",
")",
",",
"sling",
":",
"sling",
".",
"Path",
"(",
"... | // newDirectMessageService returns a new DirectMessageService. | [
"newDirectMessageService",
"returns",
"a",
"new",
"DirectMessageService",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/direct_messages.go#L83-L88 | train |
dghubble/go-twitter | twitter/stream_utils.go | newStreamResponseBodyReader | func newStreamResponseBodyReader(body io.Reader) *streamResponseBodyReader {
return &streamResponseBodyReader{reader: bufio.NewReader(body)}
} | go | func newStreamResponseBodyReader(body io.Reader) *streamResponseBodyReader {
return &streamResponseBodyReader{reader: bufio.NewReader(body)}
} | [
"func",
"newStreamResponseBodyReader",
"(",
"body",
"io",
".",
"Reader",
")",
"*",
"streamResponseBodyReader",
"{",
"return",
"&",
"streamResponseBodyReader",
"{",
"reader",
":",
"bufio",
".",
"NewReader",
"(",
"body",
")",
"}",
"\n",
"}"
] | // newStreamResponseBodyReader returns an instance of streamResponseBodyReader
// for the given Twitter stream response body. | [
"newStreamResponseBodyReader",
"returns",
"an",
"instance",
"of",
"streamResponseBodyReader",
"for",
"the",
"given",
"Twitter",
"stream",
"response",
"body",
"."
] | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/stream_utils.go#L43-L45 | train |
dghubble/go-twitter | twitter/stream_utils.go | readNext | func (r *streamResponseBodyReader) readNext() ([]byte, error) {
// Discard all the bytes from buf and continue to use the allocated memory
// space for reading the next message.
r.buf.Truncate(0)
for {
// Twitter stream messages are separated with "\r\n", and a valid
// message may sometimes contain '\n' in the middle.
// bufio.Reader.Read() can accept one byte delimiter only, so we need to
// first break out each line on '\n' and then check whether the line ends
// with "\r\n" to find message boundaries.
// https://dev.twitter.com/streaming/overview/processing
line, err := r.reader.ReadBytes('\n')
// Non-EOF error should be propagated to callers immediately.
if err != nil && err != io.EOF {
return nil, err
}
// EOF error means that we reached the end of the stream body before finding
// delimiter '\n'. If "line" is empty, it means the reader didn't read any
// data from the stream before reaching EOF and there's nothing to append to
// buf.
if err == io.EOF && len(line) == 0 {
// if buf has no data, propagate io.EOF to callers and let them know that
// we've finished processing the stream.
if r.buf.Len() == 0 {
return nil, err
}
// Otherwise, we still have a remaining stream message to return.
break
}
// If the line ends with "\r\n", it's the end of one stream message data.
if bytes.HasSuffix(line, []byte("\r\n")) {
// reader.ReadBytes() returns a slice including the delimiter itself, so
// we need to trim '\n' as well as '\r' from the end of the slice.
r.buf.Write(bytes.TrimRight(line, "\r\n"))
break
}
// Otherwise, the line is not the end of a stream message, so we append
// the line to buf and continue to scan lines.
r.buf.Write(line)
}
// Get the stream message bytes from buf. Not that Bytes() won't mark the
// returned data as "read", and we need to explicitly call Truncate(0) to
// discard from buf before writing the next stream message to buf.
return r.buf.Bytes(), nil
} | go | func (r *streamResponseBodyReader) readNext() ([]byte, error) {
// Discard all the bytes from buf and continue to use the allocated memory
// space for reading the next message.
r.buf.Truncate(0)
for {
// Twitter stream messages are separated with "\r\n", and a valid
// message may sometimes contain '\n' in the middle.
// bufio.Reader.Read() can accept one byte delimiter only, so we need to
// first break out each line on '\n' and then check whether the line ends
// with "\r\n" to find message boundaries.
// https://dev.twitter.com/streaming/overview/processing
line, err := r.reader.ReadBytes('\n')
// Non-EOF error should be propagated to callers immediately.
if err != nil && err != io.EOF {
return nil, err
}
// EOF error means that we reached the end of the stream body before finding
// delimiter '\n'. If "line" is empty, it means the reader didn't read any
// data from the stream before reaching EOF and there's nothing to append to
// buf.
if err == io.EOF && len(line) == 0 {
// if buf has no data, propagate io.EOF to callers and let them know that
// we've finished processing the stream.
if r.buf.Len() == 0 {
return nil, err
}
// Otherwise, we still have a remaining stream message to return.
break
}
// If the line ends with "\r\n", it's the end of one stream message data.
if bytes.HasSuffix(line, []byte("\r\n")) {
// reader.ReadBytes() returns a slice including the delimiter itself, so
// we need to trim '\n' as well as '\r' from the end of the slice.
r.buf.Write(bytes.TrimRight(line, "\r\n"))
break
}
// Otherwise, the line is not the end of a stream message, so we append
// the line to buf and continue to scan lines.
r.buf.Write(line)
}
// Get the stream message bytes from buf. Not that Bytes() won't mark the
// returned data as "read", and we need to explicitly call Truncate(0) to
// discard from buf before writing the next stream message to buf.
return r.buf.Bytes(), nil
} | [
"func",
"(",
"r",
"*",
"streamResponseBodyReader",
")",
"readNext",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Discard all the bytes from buf and continue to use the allocated memory",
"// space for reading the next message.",
"r",
".",
"buf",
".",
"Tr... | // readNext reads Twitter stream response body and returns the next stream
// content if exists. Returns io.EOF error if we reached the end of the stream
// and there's no more message to read. | [
"readNext",
"reads",
"Twitter",
"stream",
"response",
"body",
"and",
"returns",
"the",
"next",
"stream",
"content",
"if",
"exists",
".",
"Returns",
"io",
".",
"EOF",
"error",
"if",
"we",
"reached",
"the",
"end",
"of",
"the",
"stream",
"and",
"there",
"s",
... | 0022a70e9bee80163be82fdd74ac1d92bdebaf57 | https://github.com/dghubble/go-twitter/blob/0022a70e9bee80163be82fdd74ac1d92bdebaf57/twitter/stream_utils.go#L50-L95 | train |
logrusorgru/aurora | wrap.go | Reset | func Reset(arg interface{}) Value {
if val, ok := arg.(Value); ok {
return val.Reset()
}
return value{value: arg}
} | go | func Reset(arg interface{}) Value {
if val, ok := arg.(Value); ok {
return val.Reset()
}
return value{value: arg}
} | [
"func",
"Reset",
"(",
"arg",
"interface",
"{",
"}",
")",
"Value",
"{",
"if",
"val",
",",
"ok",
":=",
"arg",
".",
"(",
"Value",
")",
";",
"ok",
"{",
"return",
"val",
".",
"Reset",
"(",
")",
"\n",
"}",
"\n",
"return",
"value",
"{",
"value",
":",
... | // Reset wraps given argument returning Value
// without formats and colors. | [
"Reset",
"wraps",
"given",
"argument",
"returning",
"Value",
"without",
"formats",
"and",
"colors",
"."
] | cea283e61946ad8227cc02a24201407a2c9e5182 | https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/wrap.go#L51-L56 | train |
logrusorgru/aurora | color.go | Nos | func (c Color) Nos(zero bool) string {
return string(c.appendNos(make([]byte, 0, 59), zero))
} | go | func (c Color) Nos(zero bool) string {
return string(c.appendNos(make([]byte, 0, 59), zero))
} | [
"func",
"(",
"c",
"Color",
")",
"Nos",
"(",
"zero",
"bool",
")",
"string",
"{",
"return",
"string",
"(",
"c",
".",
"appendNos",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"59",
")",
",",
"zero",
")",
")",
"\n",
"}"
] | // Nos returns string like 1;7;31;45. It
// may be an empty string for empty color.
// If the zero is true, then the string
// is prepended with 0; | [
"Nos",
"returns",
"string",
"like",
"1",
";",
"7",
";",
"31",
";",
"45",
".",
"It",
"may",
"be",
"an",
"empty",
"string",
"for",
"empty",
"color",
".",
"If",
"the",
"zero",
"is",
"true",
"then",
"the",
"string",
"is",
"prepended",
"with",
"0",
";"
... | cea283e61946ad8227cc02a24201407a2c9e5182 | https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/color.go#L186-L188 | train |
logrusorgru/aurora | color.go | appendSemi | func appendSemi(bs []byte, semi bool, vals ...byte) []byte {
if semi {
bs = append(bs, ';')
}
return append(bs, vals...)
} | go | func appendSemi(bs []byte, semi bool, vals ...byte) []byte {
if semi {
bs = append(bs, ';')
}
return append(bs, vals...)
} | [
"func",
"appendSemi",
"(",
"bs",
"[",
"]",
"byte",
",",
"semi",
"bool",
",",
"vals",
"...",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"semi",
"{",
"bs",
"=",
"append",
"(",
"bs",
",",
"';'",
")",
"\n",
"}",
"\n",
"return",
"append",
"(",
"bs",
... | // if the semi is true, then prepend with semicolon | [
"if",
"the",
"semi",
"is",
"true",
"then",
"prepend",
"with",
"semicolon"
] | cea283e61946ad8227cc02a24201407a2c9e5182 | https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/color.go#L198-L203 | train |
logrusorgru/aurora | color.go | appendNos | func (c Color) appendNos(bs []byte, zero bool) []byte {
if zero {
bs = append(bs, '0') // reset previous
}
// formats
//
if c&maskFm != 0 {
// 1-2
// don't combine bold and faint using only on of them, preferring bold
if c&BoldFm != 0 {
bs = appendSemi(bs, zero, '1')
} else if c&FaintFm != 0 {
bs = appendSemi(bs, zero, '2')
}
// 3-9
const mask9 = ItalicFm | UnderlineFm |
SlowBlinkFm | RapidBlinkFm |
ReverseFm | ConcealFm | CrossedOutFm
if c&mask9 != 0 {
bs = c.appendFm9(bs, zero)
}
// 20-21
const (
mask21 = FrakturFm | DoublyUnderlineFm
mask9i = BoldFm | FaintFm | mask9
)
if c&mask21 != 0 {
bs = appendCond(bs, c&FrakturFm != 0,
zero || c&mask9i != 0,
'2', '0')
bs = appendCond(bs, c&DoublyUnderlineFm != 0,
zero || c&(mask9i|FrakturFm) != 0,
'2', '1')
}
// 50-53
const (
mask53 = FramedFm | EncircledFm | OverlinedFm
mask21i = mask9i | mask21
)
if c&mask53 != 0 {
bs = appendCond(bs, c&FramedFm != 0,
zero || c&mask21i != 0,
'5', '1')
bs = appendCond(bs, c&EncircledFm != 0,
zero || c&(mask21i|FramedFm) != 0,
'5', '2')
bs = appendCond(bs, c&OverlinedFm != 0,
zero || c&(mask21i|FramedFm|EncircledFm) != 0,
'5', '3')
}
}
// foreground
if c&maskFg != 0 {
bs = c.appendFg(bs, zero)
}
// background
if c&maskBg != 0 {
bs = c.appendBg(bs, zero)
}
return bs
} | go | func (c Color) appendNos(bs []byte, zero bool) []byte {
if zero {
bs = append(bs, '0') // reset previous
}
// formats
//
if c&maskFm != 0 {
// 1-2
// don't combine bold and faint using only on of them, preferring bold
if c&BoldFm != 0 {
bs = appendSemi(bs, zero, '1')
} else if c&FaintFm != 0 {
bs = appendSemi(bs, zero, '2')
}
// 3-9
const mask9 = ItalicFm | UnderlineFm |
SlowBlinkFm | RapidBlinkFm |
ReverseFm | ConcealFm | CrossedOutFm
if c&mask9 != 0 {
bs = c.appendFm9(bs, zero)
}
// 20-21
const (
mask21 = FrakturFm | DoublyUnderlineFm
mask9i = BoldFm | FaintFm | mask9
)
if c&mask21 != 0 {
bs = appendCond(bs, c&FrakturFm != 0,
zero || c&mask9i != 0,
'2', '0')
bs = appendCond(bs, c&DoublyUnderlineFm != 0,
zero || c&(mask9i|FrakturFm) != 0,
'2', '1')
}
// 50-53
const (
mask53 = FramedFm | EncircledFm | OverlinedFm
mask21i = mask9i | mask21
)
if c&mask53 != 0 {
bs = appendCond(bs, c&FramedFm != 0,
zero || c&mask21i != 0,
'5', '1')
bs = appendCond(bs, c&EncircledFm != 0,
zero || c&(mask21i|FramedFm) != 0,
'5', '2')
bs = appendCond(bs, c&OverlinedFm != 0,
zero || c&(mask21i|FramedFm|EncircledFm) != 0,
'5', '3')
}
}
// foreground
if c&maskFg != 0 {
bs = c.appendFg(bs, zero)
}
// background
if c&maskBg != 0 {
bs = c.appendBg(bs, zero)
}
return bs
} | [
"func",
"(",
"c",
"Color",
")",
"appendNos",
"(",
"bs",
"[",
"]",
"byte",
",",
"zero",
"bool",
")",
"[",
"]",
"byte",
"{",
"if",
"zero",
"{",
"bs",
"=",
"append",
"(",
"bs",
",",
"'0'",
")",
"// reset previous",
"\n",
"}",
"\n\n",
"// formats",
"... | // append 1;3;38;5;216 like string that represents ANSI
// color of the Color; the zero argument requires
// appending of '0' before to reset previous format
// and colors | [
"append",
"1",
";",
"3",
";",
"38",
";",
"5",
";",
"216",
"like",
"string",
"that",
"represents",
"ANSI",
"color",
"of",
"the",
"Color",
";",
"the",
"zero",
"argument",
"requires",
"appending",
"of",
"0",
"before",
"to",
"reset",
"previous",
"format",
... | cea283e61946ad8227cc02a24201407a2c9e5182 | https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/color.go#L309-L388 | train |
gosuri/uilive | writer.go | New | func New() *Writer {
termWidth, _ = getTermSize()
if termWidth != 0 {
overFlowHandled = true
}
return &Writer{
Out: Out,
RefreshInterval: RefreshInterval,
mtx: &sync.Mutex{},
}
} | go | func New() *Writer {
termWidth, _ = getTermSize()
if termWidth != 0 {
overFlowHandled = true
}
return &Writer{
Out: Out,
RefreshInterval: RefreshInterval,
mtx: &sync.Mutex{},
}
} | [
"func",
"New",
"(",
")",
"*",
"Writer",
"{",
"termWidth",
",",
"_",
"=",
"getTermSize",
"(",
")",
"\n",
"if",
"termWidth",
"!=",
"0",
"{",
"overFlowHandled",
"=",
"true",
"\n",
"}",
"\n\n",
"return",
"&",
"Writer",
"{",
"Out",
":",
"Out",
",",
"Ref... | // New returns a new Writer with defaults | [
"New",
"returns",
"a",
"new",
"Writer",
"with",
"defaults"
] | 810653011da975cf3ac54bf7aea22d5c9e49e317 | https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L59-L71 | train |
gosuri/uilive | writer.go | Flush | func (w *Writer) Flush() error {
w.mtx.Lock()
defer w.mtx.Unlock()
// do nothing if buffer is empty
if len(w.buf.Bytes()) == 0 {
return nil
}
w.clearLines()
lines := 0
var currentLine bytes.Buffer
for _, b := range w.buf.Bytes() {
if b == '\n' {
lines++
currentLine.Reset()
} else {
currentLine.Write([]byte{b})
if overFlowHandled && currentLine.Len() > termWidth {
lines++
currentLine.Reset()
}
}
}
w.lineCount = lines
_, err := w.Out.Write(w.buf.Bytes())
w.buf.Reset()
return err
} | go | func (w *Writer) Flush() error {
w.mtx.Lock()
defer w.mtx.Unlock()
// do nothing if buffer is empty
if len(w.buf.Bytes()) == 0 {
return nil
}
w.clearLines()
lines := 0
var currentLine bytes.Buffer
for _, b := range w.buf.Bytes() {
if b == '\n' {
lines++
currentLine.Reset()
} else {
currentLine.Write([]byte{b})
if overFlowHandled && currentLine.Len() > termWidth {
lines++
currentLine.Reset()
}
}
}
w.lineCount = lines
_, err := w.Out.Write(w.buf.Bytes())
w.buf.Reset()
return err
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Flush",
"(",
")",
"error",
"{",
"w",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// do nothing if buffer is empty",
"if",
"len",
"(",
"w",
".",
"buf",
... | // Flush writes to the out and resets the buffer. It should be called after the last call to Write to ensure that any data buffered in the Writer is written to output.
// Any incomplete escape sequence at the end is considered complete for formatting purposes.
// An error is returned if the contents of the buffer cannot be written to the underlying output stream | [
"Flush",
"writes",
"to",
"the",
"out",
"and",
"resets",
"the",
"buffer",
".",
"It",
"should",
"be",
"called",
"after",
"the",
"last",
"call",
"to",
"Write",
"to",
"ensure",
"that",
"any",
"data",
"buffered",
"in",
"the",
"Writer",
"is",
"written",
"to",
... | 810653011da975cf3ac54bf7aea22d5c9e49e317 | https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L76-L104 | train |
gosuri/uilive | writer.go | Start | func (w *Writer) Start() {
if w.ticker == nil {
w.ticker = time.NewTicker(w.RefreshInterval)
w.tdone = make(chan bool, 1)
}
go w.Listen()
} | go | func (w *Writer) Start() {
if w.ticker == nil {
w.ticker = time.NewTicker(w.RefreshInterval)
w.tdone = make(chan bool, 1)
}
go w.Listen()
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Start",
"(",
")",
"{",
"if",
"w",
".",
"ticker",
"==",
"nil",
"{",
"w",
".",
"ticker",
"=",
"time",
".",
"NewTicker",
"(",
"w",
".",
"RefreshInterval",
")",
"\n",
"w",
".",
"tdone",
"=",
"make",
"(",
"chan... | // Start starts the listener in a non-blocking manner | [
"Start",
"starts",
"the",
"listener",
"in",
"a",
"non",
"-",
"blocking",
"manner"
] | 810653011da975cf3ac54bf7aea22d5c9e49e317 | https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L107-L114 | train |
gosuri/uilive | writer.go | Listen | func (w *Writer) Listen() {
for {
select {
case <-w.ticker.C:
if w.ticker != nil {
w.Flush()
}
case <-w.tdone:
w.mtx.Lock()
w.ticker.Stop()
w.ticker = nil
w.mtx.Unlock()
return
}
}
} | go | func (w *Writer) Listen() {
for {
select {
case <-w.ticker.C:
if w.ticker != nil {
w.Flush()
}
case <-w.tdone:
w.mtx.Lock()
w.ticker.Stop()
w.ticker = nil
w.mtx.Unlock()
return
}
}
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Listen",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"w",
".",
"ticker",
".",
"C",
":",
"if",
"w",
".",
"ticker",
"!=",
"nil",
"{",
"w",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n",
"case",
"<-... | // Listen listens for updates to the writer's buffer and flushes to the out provided. It blocks the runtime. | [
"Listen",
"listens",
"for",
"updates",
"to",
"the",
"writer",
"s",
"buffer",
"and",
"flushes",
"to",
"the",
"out",
"provided",
".",
"It",
"blocks",
"the",
"runtime",
"."
] | 810653011da975cf3ac54bf7aea22d5c9e49e317 | https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L123-L138 | train |
gosuri/uilive | writer.go | Write | func (w *Writer) Write(buf []byte) (n int, err error) {
w.mtx.Lock()
defer w.mtx.Unlock()
return w.buf.Write(buf)
} | go | func (w *Writer) Write(buf []byte) (n int, err error) {
w.mtx.Lock()
defer w.mtx.Unlock()
return w.buf.Write(buf)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Write",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"w",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"return... | // Write save the contents of buf to the writer b. The only errors returned are ones encountered while writing to the underlying buffer. | [
"Write",
"save",
"the",
"contents",
"of",
"buf",
"to",
"the",
"writer",
"b",
".",
"The",
"only",
"errors",
"returned",
"are",
"ones",
"encountered",
"while",
"writing",
"to",
"the",
"underlying",
"buffer",
"."
] | 810653011da975cf3ac54bf7aea22d5c9e49e317 | https://github.com/gosuri/uilive/blob/810653011da975cf3ac54bf7aea22d5c9e49e317/writer.go#L141-L145 | train |
ory/dockertest | docker/pkg/jsonmessage/jsonmessage.go | Display | func (jm *JSONMessage) Display(out io.Writer, termInfo termInfo) error {
if jm.Error != nil {
if jm.Error.Code == 401 {
return fmt.Errorf("authentication is required")
}
return jm.Error
}
var endl string
if termInfo != nil && jm.Stream == "" && jm.Progress != nil {
clearLine(out, termInfo)
endl = "\r"
fmt.Fprintf(out, endl)
} else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal
return nil
}
if jm.TimeNano != 0 {
fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(RFC3339NanoFixed))
} else if jm.Time != 0 {
fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(RFC3339NanoFixed))
}
if jm.ID != "" {
fmt.Fprintf(out, "%s: ", jm.ID)
}
if jm.From != "" {
fmt.Fprintf(out, "(from %s) ", jm.From)
}
if jm.Progress != nil && termInfo != nil {
fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl)
} else if jm.ProgressMessage != "" { //deprecated
fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl)
} else if jm.Stream != "" {
fmt.Fprintf(out, "%s%s", jm.Stream, endl)
} else {
fmt.Fprintf(out, "%s%s\n", jm.Status, endl)
}
return nil
} | go | func (jm *JSONMessage) Display(out io.Writer, termInfo termInfo) error {
if jm.Error != nil {
if jm.Error.Code == 401 {
return fmt.Errorf("authentication is required")
}
return jm.Error
}
var endl string
if termInfo != nil && jm.Stream == "" && jm.Progress != nil {
clearLine(out, termInfo)
endl = "\r"
fmt.Fprintf(out, endl)
} else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal
return nil
}
if jm.TimeNano != 0 {
fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(RFC3339NanoFixed))
} else if jm.Time != 0 {
fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(RFC3339NanoFixed))
}
if jm.ID != "" {
fmt.Fprintf(out, "%s: ", jm.ID)
}
if jm.From != "" {
fmt.Fprintf(out, "(from %s) ", jm.From)
}
if jm.Progress != nil && termInfo != nil {
fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl)
} else if jm.ProgressMessage != "" { //deprecated
fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl)
} else if jm.Stream != "" {
fmt.Fprintf(out, "%s%s", jm.Stream, endl)
} else {
fmt.Fprintf(out, "%s%s\n", jm.Status, endl)
}
return nil
} | [
"func",
"(",
"jm",
"*",
"JSONMessage",
")",
"Display",
"(",
"out",
"io",
".",
"Writer",
",",
"termInfo",
"termInfo",
")",
"error",
"{",
"if",
"jm",
".",
"Error",
"!=",
"nil",
"{",
"if",
"jm",
".",
"Error",
".",
"Code",
"==",
"401",
"{",
"return",
... | // Display displays the JSONMessage to `out`. `termInfo` is non-nil if `out`
// is a terminal. If this is the case, it will erase the entire current line
// when displaying the progressbar. | [
"Display",
"displays",
"the",
"JSONMessage",
"to",
"out",
".",
"termInfo",
"is",
"non",
"-",
"nil",
"if",
"out",
"is",
"a",
"terminal",
".",
"If",
"this",
"is",
"the",
"case",
"it",
"will",
"erase",
"the",
"entire",
"current",
"line",
"when",
"displaying... | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/pkg/jsonmessage/jsonmessage.go#L207-L243 | train |
ory/dockertest | docker/client_unix.go | initializeNativeClient | func (c *Client) initializeNativeClient(trFunc func() *http.Transport) {
if c.endpointURL.Scheme != unixProtocol {
return
}
sockPath := c.endpointURL.Path
tr := trFunc()
tr.Dial = func(network, addr string) (net.Conn, error) {
return c.Dialer.Dial(unixProtocol, sockPath)
}
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return c.Dialer.Dial(unixProtocol, sockPath)
}
c.HTTPClient.Transport = tr
} | go | func (c *Client) initializeNativeClient(trFunc func() *http.Transport) {
if c.endpointURL.Scheme != unixProtocol {
return
}
sockPath := c.endpointURL.Path
tr := trFunc()
tr.Dial = func(network, addr string) (net.Conn, error) {
return c.Dialer.Dial(unixProtocol, sockPath)
}
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return c.Dialer.Dial(unixProtocol, sockPath)
}
c.HTTPClient.Transport = tr
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"initializeNativeClient",
"(",
"trFunc",
"func",
"(",
")",
"*",
"http",
".",
"Transport",
")",
"{",
"if",
"c",
".",
"endpointURL",
".",
"Scheme",
"!=",
"unixProtocol",
"{",
"return",
"\n",
"}",
"\n",
"sockPath",
":... | // initializeNativeClient initializes the native Unix domain socket client on
// Unix-style operating systems | [
"initializeNativeClient",
"initializes",
"the",
"native",
"Unix",
"domain",
"socket",
"client",
"on",
"Unix",
"-",
"style",
"operating",
"systems"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client_unix.go#L17-L32 | train |
ory/dockertest | docker/distribution.go | InspectDistribution | func (c *Client) InspectDistribution(name string) (*registry.DistributionInspect, error) {
path := "/distribution/" + name + "/json"
resp, err := c.do("GET", path, doOptions{})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var distributionInspect registry.DistributionInspect
if err := json.NewDecoder(resp.Body).Decode(&distributionInspect); err != nil {
return nil, err
}
return &distributionInspect, nil
} | go | func (c *Client) InspectDistribution(name string) (*registry.DistributionInspect, error) {
path := "/distribution/" + name + "/json"
resp, err := c.do("GET", path, doOptions{})
if err != nil {
return nil, err
}
defer resp.Body.Close()
var distributionInspect registry.DistributionInspect
if err := json.NewDecoder(resp.Body).Decode(&distributionInspect); err != nil {
return nil, err
}
return &distributionInspect, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"InspectDistribution",
"(",
"name",
"string",
")",
"(",
"*",
"registry",
".",
"DistributionInspect",
",",
"error",
")",
"{",
"path",
":=",
"\"",
"\"",
"+",
"name",
"+",
"\"",
"\"",
"\n",
"resp",
",",
"err",
":=",... | // InspectDistribution returns image digest and platform information by contacting the registry | [
"InspectDistribution",
"returns",
"image",
"digest",
"and",
"platform",
"information",
"by",
"contacting",
"the",
"registry"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/distribution.go#L14-L26 | train |
ory/dockertest | docker/pkg/system/lcow.go | IsOSSupported | func IsOSSupported(os string) bool {
if runtime.GOOS == os {
return true
}
if LCOWSupported() && os == "linux" {
return true
}
return false
} | go | func IsOSSupported(os string) bool {
if runtime.GOOS == os {
return true
}
if LCOWSupported() && os == "linux" {
return true
}
return false
} | [
"func",
"IsOSSupported",
"(",
"os",
"string",
")",
"bool",
"{",
"if",
"runtime",
".",
"GOOS",
"==",
"os",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"LCOWSupported",
"(",
")",
"&&",
"os",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",... | // IsOSSupported determines if an operating system is supported by the host | [
"IsOSSupported",
"determines",
"if",
"an",
"operating",
"system",
"is",
"supported",
"by",
"the",
"host"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/pkg/system/lcow.go#L61-L69 | train |
ory/dockertest | docker/event.go | AddEventListener | func (c *Client) AddEventListener(listener chan<- *APIEvents) error {
var err error
if !c.eventMonitor.isEnabled() {
err = c.eventMonitor.enableEventMonitoring(c)
if err != nil {
return err
}
}
return c.eventMonitor.addListener(listener)
} | go | func (c *Client) AddEventListener(listener chan<- *APIEvents) error {
var err error
if !c.eventMonitor.isEnabled() {
err = c.eventMonitor.enableEventMonitoring(c)
if err != nil {
return err
}
}
return c.eventMonitor.addListener(listener)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AddEventListener",
"(",
"listener",
"chan",
"<-",
"*",
"APIEvents",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"if",
"!",
"c",
".",
"eventMonitor",
".",
"isEnabled",
"(",
")",
"{",
"err",
"=",
"c",
".",
"... | // AddEventListener adds a new listener to container events in the Docker API.
//
// The parameter is a channel through which events will be sent. | [
"AddEventListener",
"adds",
"a",
"new",
"listener",
"to",
"container",
"events",
"in",
"the",
"Docker",
"API",
".",
"The",
"parameter",
"is",
"a",
"channel",
"through",
"which",
"events",
"will",
"be",
"sent",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/event.go#L95-L104 | train |
ory/dockertest | docker/event.go | RemoveEventListener | func (c *Client) RemoveEventListener(listener chan *APIEvents) error {
err := c.eventMonitor.removeListener(listener)
if err != nil {
return err
}
if c.eventMonitor.listernersCount() == 0 {
c.eventMonitor.disableEventMonitoring()
}
return nil
} | go | func (c *Client) RemoveEventListener(listener chan *APIEvents) error {
err := c.eventMonitor.removeListener(listener)
if err != nil {
return err
}
if c.eventMonitor.listernersCount() == 0 {
c.eventMonitor.disableEventMonitoring()
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"RemoveEventListener",
"(",
"listener",
"chan",
"*",
"APIEvents",
")",
"error",
"{",
"err",
":=",
"c",
".",
"eventMonitor",
".",
"removeListener",
"(",
"listener",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // RemoveEventListener removes a listener from the monitor. | [
"RemoveEventListener",
"removes",
"a",
"listener",
"from",
"the",
"monitor",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/event.go#L107-L116 | train |
ory/dockertest | docker/event.go | transformEvent | func transformEvent(event *APIEvents) {
// if event version is <= 1.21 there will be no Action and no Type
if event.Action == "" && event.Type == "" {
event.Action = event.Status
event.Actor.ID = event.ID
event.Actor.Attributes = map[string]string{}
switch event.Status {
case "delete", "import", "pull", "push", "tag", "untag":
event.Type = "image"
default:
event.Type = "container"
if event.From != "" {
event.Actor.Attributes["image"] = event.From
}
}
} else {
if event.Status == "" {
if event.Type == "image" || event.Type == "container" {
event.Status = event.Action
} else {
// Because just the Status has been overloaded with different Types
// if an event is not for an image or a container, we prepend the type
// to avoid problems for people relying on actions being only for
// images and containers
event.Status = event.Type + ":" + event.Action
}
}
if event.ID == "" {
event.ID = event.Actor.ID
}
if event.From == "" {
event.From = event.Actor.Attributes["image"]
}
}
} | go | func transformEvent(event *APIEvents) {
// if event version is <= 1.21 there will be no Action and no Type
if event.Action == "" && event.Type == "" {
event.Action = event.Status
event.Actor.ID = event.ID
event.Actor.Attributes = map[string]string{}
switch event.Status {
case "delete", "import", "pull", "push", "tag", "untag":
event.Type = "image"
default:
event.Type = "container"
if event.From != "" {
event.Actor.Attributes["image"] = event.From
}
}
} else {
if event.Status == "" {
if event.Type == "image" || event.Type == "container" {
event.Status = event.Action
} else {
// Because just the Status has been overloaded with different Types
// if an event is not for an image or a container, we prepend the type
// to avoid problems for people relying on actions being only for
// images and containers
event.Status = event.Type + ":" + event.Action
}
}
if event.ID == "" {
event.ID = event.Actor.ID
}
if event.From == "" {
event.From = event.Actor.Attributes["image"]
}
}
} | [
"func",
"transformEvent",
"(",
"event",
"*",
"APIEvents",
")",
"{",
"// if event version is <= 1.21 there will be no Action and no Type",
"if",
"event",
".",
"Action",
"==",
"\"",
"\"",
"&&",
"event",
".",
"Type",
"==",
"\"",
"\"",
"{",
"event",
".",
"Action",
"... | // transformEvent takes an event and determines what version it is from
// then populates both versions of the event | [
"transformEvent",
"takes",
"an",
"event",
"and",
"determines",
"what",
"version",
"it",
"is",
"from",
"then",
"populates",
"both",
"versions",
"of",
"the",
"event"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/event.go#L376-L410 | train |
ory/dockertest | docker/container.go | Proto | func (p Port) Proto() string {
parts := strings.Split(string(p), "/")
if len(parts) == 1 {
return "tcp"
}
return parts[1]
} | go | func (p Port) Proto() string {
parts := strings.Split(string(p), "/")
if len(parts) == 1 {
return "tcp"
}
return parts[1]
} | [
"func",
"(",
"p",
"Port",
")",
"Proto",
"(",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"string",
"(",
"p",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
"{",
"return",
"\"",
"\"",
"\n",
"}"... | // Proto returns the name of the protocol. | [
"Proto",
"returns",
"the",
"name",
"of",
"the",
"protocol",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/container.go#L109-L115 | train |
ory/dockertest | docker/container.go | String | func (s *State) String() string {
if s.Running {
if s.Paused {
return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
}
if s.Restarting {
return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
}
return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
}
if s.RemovalInProgress {
return "Removal In Progress"
}
if s.Dead {
return "Dead"
}
if s.StartedAt.IsZero() {
return "Created"
}
if s.FinishedAt.IsZero() {
return ""
}
return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
} | go | func (s *State) String() string {
if s.Running {
if s.Paused {
return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
}
if s.Restarting {
return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
}
return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
}
if s.RemovalInProgress {
return "Removal In Progress"
}
if s.Dead {
return "Dead"
}
if s.StartedAt.IsZero() {
return "Created"
}
if s.FinishedAt.IsZero() {
return ""
}
return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
} | [
"func",
"(",
"s",
"*",
"State",
")",
"String",
"(",
")",
"string",
"{",
"if",
"s",
".",
"Running",
"{",
"if",
"s",
".",
"Paused",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"units",
".",
"HumanDuration",
"(",
"time",
".",
"Now",
... | // String returns a human-readable description of the state | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"description",
"of",
"the",
"state"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/container.go#L150-L179 | train |
ory/dockertest | docker/container.go | StateString | func (s *State) StateString() string {
if s.Running {
if s.Paused {
return "paused"
}
if s.Restarting {
return "restarting"
}
return "running"
}
if s.Dead {
return "dead"
}
if s.StartedAt.IsZero() {
return "created"
}
return "exited"
} | go | func (s *State) StateString() string {
if s.Running {
if s.Paused {
return "paused"
}
if s.Restarting {
return "restarting"
}
return "running"
}
if s.Dead {
return "dead"
}
if s.StartedAt.IsZero() {
return "created"
}
return "exited"
} | [
"func",
"(",
"s",
"*",
"State",
")",
"StateString",
"(",
")",
"string",
"{",
"if",
"s",
".",
"Running",
"{",
"if",
"s",
".",
"Paused",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"s",
".",
"Restarting",
"{",
"return",
"\"",
"\"",
"\n",
"}... | // StateString returns a single string to describe state | [
"StateString",
"returns",
"a",
"single",
"string",
"to",
"describe",
"state"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/container.go#L182-L202 | train |
ory/dockertest | docker/container.go | PortMappingAPI | func (settings *NetworkSettings) PortMappingAPI() []APIPort {
var mapping []APIPort
for port, bindings := range settings.Ports {
p, _ := parsePort(port.Port())
if len(bindings) == 0 {
mapping = append(mapping, APIPort{
PrivatePort: int64(p),
Type: port.Proto(),
})
continue
}
for _, binding := range bindings {
p, _ := parsePort(port.Port())
h, _ := parsePort(binding.HostPort)
mapping = append(mapping, APIPort{
PrivatePort: int64(p),
PublicPort: int64(h),
Type: port.Proto(),
IP: binding.HostIP,
})
}
}
return mapping
} | go | func (settings *NetworkSettings) PortMappingAPI() []APIPort {
var mapping []APIPort
for port, bindings := range settings.Ports {
p, _ := parsePort(port.Port())
if len(bindings) == 0 {
mapping = append(mapping, APIPort{
PrivatePort: int64(p),
Type: port.Proto(),
})
continue
}
for _, binding := range bindings {
p, _ := parsePort(port.Port())
h, _ := parsePort(binding.HostPort)
mapping = append(mapping, APIPort{
PrivatePort: int64(p),
PublicPort: int64(h),
Type: port.Proto(),
IP: binding.HostIP,
})
}
}
return mapping
} | [
"func",
"(",
"settings",
"*",
"NetworkSettings",
")",
"PortMappingAPI",
"(",
")",
"[",
"]",
"APIPort",
"{",
"var",
"mapping",
"[",
"]",
"APIPort",
"\n",
"for",
"port",
",",
"bindings",
":=",
"range",
"settings",
".",
"Ports",
"{",
"p",
",",
"_",
":=",
... | // PortMappingAPI translates the port mappings as contained in NetworkSettings
// into the format in which they would appear when returned by the API | [
"PortMappingAPI",
"translates",
"the",
"port",
"mappings",
"as",
"contained",
"in",
"NetworkSettings",
"into",
"the",
"format",
"in",
"which",
"they",
"would",
"appear",
"when",
"returned",
"by",
"the",
"API"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/container.go#L253-L276 | train |
ory/dockertest | docker/client.go | NewClient | func NewClient(endpoint string) (*Client, error) {
client, err := NewVersionedClient(endpoint, "")
if err != nil {
return nil, err
}
client.SkipServerVersionCheck = true
return client, nil
} | go | func NewClient(endpoint string) (*Client, error) {
client, err := NewVersionedClient(endpoint, "")
if err != nil {
return nil, err
}
client.SkipServerVersionCheck = true
return client, nil
} | [
"func",
"NewClient",
"(",
"endpoint",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"NewVersionedClient",
"(",
"endpoint",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err"... | // NewClient returns a Client instance ready for communication with the given
// server endpoint. It will use the latest remote API version available in the
// server. | [
"NewClient",
"returns",
"a",
"Client",
"instance",
"ready",
"for",
"communication",
"with",
"the",
"given",
"server",
"endpoint",
".",
"It",
"will",
"use",
"the",
"latest",
"remote",
"API",
"version",
"available",
"in",
"the",
"server",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L165-L172 | train |
ory/dockertest | docker/client.go | NewTLSClient | func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) {
client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "")
if err != nil {
return nil, err
}
client.SkipServerVersionCheck = true
return client, nil
} | go | func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) {
client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "")
if err != nil {
return nil, err
}
client.SkipServerVersionCheck = true
return client, nil
} | [
"func",
"NewTLSClient",
"(",
"endpoint",
"string",
",",
"cert",
",",
"key",
",",
"ca",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"NewVersionedTLSClient",
"(",
"endpoint",
",",
"cert",
",",
"key",
",",
"ca",
... | // NewTLSClient returns a Client instance ready for TLS communications with the givens
// server endpoint, key and certificates . It will use the latest remote API version
// available in the server. | [
"NewTLSClient",
"returns",
"a",
"Client",
"instance",
"ready",
"for",
"TLS",
"communications",
"with",
"the",
"givens",
"server",
"endpoint",
"key",
"and",
"certificates",
".",
"It",
"will",
"use",
"the",
"latest",
"remote",
"API",
"version",
"available",
"in",
... | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L177-L184 | train |
ory/dockertest | docker/client.go | NewVersionedClient | func NewVersionedClient(endpoint string, apiVersionString string) (*Client, error) {
u, err := parseEndpoint(endpoint, false)
if err != nil {
return nil, err
}
var requestedAPIVersion APIVersion
if strings.Contains(apiVersionString, ".") {
requestedAPIVersion, err = NewAPIVersion(apiVersionString)
if err != nil {
return nil, err
}
}
c := &Client{
HTTPClient: defaultClient(),
Dialer: &net.Dialer{},
endpoint: endpoint,
endpointURL: u,
eventMonitor: new(eventMonitoringState),
requestedAPIVersion: requestedAPIVersion,
}
c.initializeNativeClient(defaultTransport)
return c, nil
} | go | func NewVersionedClient(endpoint string, apiVersionString string) (*Client, error) {
u, err := parseEndpoint(endpoint, false)
if err != nil {
return nil, err
}
var requestedAPIVersion APIVersion
if strings.Contains(apiVersionString, ".") {
requestedAPIVersion, err = NewAPIVersion(apiVersionString)
if err != nil {
return nil, err
}
}
c := &Client{
HTTPClient: defaultClient(),
Dialer: &net.Dialer{},
endpoint: endpoint,
endpointURL: u,
eventMonitor: new(eventMonitoringState),
requestedAPIVersion: requestedAPIVersion,
}
c.initializeNativeClient(defaultTransport)
return c, nil
} | [
"func",
"NewVersionedClient",
"(",
"endpoint",
"string",
",",
"apiVersionString",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"u",
",",
"err",
":=",
"parseEndpoint",
"(",
"endpoint",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // NewVersionedClient returns a Client instance ready for communication with
// the given server endpoint, using a specific remote API version. | [
"NewVersionedClient",
"returns",
"a",
"Client",
"instance",
"ready",
"for",
"communication",
"with",
"the",
"given",
"server",
"endpoint",
"using",
"a",
"specific",
"remote",
"API",
"version",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L200-L222 | train |
ory/dockertest | docker/client.go | NewVersionedTLSClient | func NewVersionedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) {
var certPEMBlock []byte
var keyPEMBlock []byte
var caPEMCert []byte
if _, err := os.Stat(cert); !os.IsNotExist(err) {
certPEMBlock, err = ioutil.ReadFile(cert)
if err != nil {
return nil, err
}
}
if _, err := os.Stat(key); !os.IsNotExist(err) {
keyPEMBlock, err = ioutil.ReadFile(key)
if err != nil {
return nil, err
}
}
if _, err := os.Stat(ca); !os.IsNotExist(err) {
caPEMCert, err = ioutil.ReadFile(ca)
if err != nil {
return nil, err
}
}
return NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, apiVersionString)
} | go | func NewVersionedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) {
var certPEMBlock []byte
var keyPEMBlock []byte
var caPEMCert []byte
if _, err := os.Stat(cert); !os.IsNotExist(err) {
certPEMBlock, err = ioutil.ReadFile(cert)
if err != nil {
return nil, err
}
}
if _, err := os.Stat(key); !os.IsNotExist(err) {
keyPEMBlock, err = ioutil.ReadFile(key)
if err != nil {
return nil, err
}
}
if _, err := os.Stat(ca); !os.IsNotExist(err) {
caPEMCert, err = ioutil.ReadFile(ca)
if err != nil {
return nil, err
}
}
return NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, apiVersionString)
} | [
"func",
"NewVersionedTLSClient",
"(",
"endpoint",
"string",
",",
"cert",
",",
"key",
",",
"ca",
",",
"apiVersionString",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"var",
"certPEMBlock",
"[",
"]",
"byte",
"\n",
"var",
"keyPEMBlock",
"[",
... | // NewVersionedTLSClient returns a Client instance ready for TLS communications with the givens
// server endpoint, key and certificates, using a specific remote API version. | [
"NewVersionedTLSClient",
"returns",
"a",
"Client",
"instance",
"ready",
"for",
"TLS",
"communications",
"with",
"the",
"givens",
"server",
"endpoint",
"key",
"and",
"certificates",
"using",
"a",
"specific",
"remote",
"API",
"version",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L239-L262 | train |
ory/dockertest | docker/client.go | SetTimeout | func (c *Client) SetTimeout(t time.Duration) {
if c.HTTPClient != nil {
c.HTTPClient.Timeout = t
}
} | go | func (c *Client) SetTimeout(t time.Duration) {
if c.HTTPClient != nil {
c.HTTPClient.Timeout = t
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"{",
"if",
"c",
".",
"HTTPClient",
"!=",
"nil",
"{",
"c",
".",
"HTTPClient",
".",
"Timeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // SetTimeout takes a timeout and applies it to the HTTPClient. It should not
// be called concurrently with any other Client methods. | [
"SetTimeout",
"takes",
"a",
"timeout",
"and",
"applies",
"it",
"to",
"the",
"HTTPClient",
".",
"It",
"should",
"not",
"be",
"called",
"concurrently",
"with",
"any",
"other",
"Client",
"methods",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L355-L359 | train |
ory/dockertest | docker/client.go | chooseError | func chooseError(ctx context.Context, err error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return err
}
} | go | func chooseError(ctx context.Context, err error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return err
}
} | [
"func",
"chooseError",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
")",
"error",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"default",
":",
"return",
"err",
"\n"... | // if error in context, return that instead of generic http error | [
"if",
"error",
"in",
"context",
"return",
"that",
"instead",
"of",
"generic",
"http",
"error"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L511-L518 | train |
ory/dockertest | docker/client.go | getFakeNativeURL | func (c *Client) getFakeNativeURL(path string) string {
u := *c.endpointURL // Copy.
// Override URL so that net/http will not complain.
u.Scheme = "http"
u.Host = "unix.sock" // Doesn't matter what this is - it's not used.
u.Path = ""
urlStr := strings.TrimRight(u.String(), "/")
if c.requestedAPIVersion != nil {
return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path)
}
return fmt.Sprintf("%s%s", urlStr, path)
} | go | func (c *Client) getFakeNativeURL(path string) string {
u := *c.endpointURL // Copy.
// Override URL so that net/http will not complain.
u.Scheme = "http"
u.Host = "unix.sock" // Doesn't matter what this is - it's not used.
u.Path = ""
urlStr := strings.TrimRight(u.String(), "/")
if c.requestedAPIVersion != nil {
return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path)
}
return fmt.Sprintf("%s%s", urlStr, path)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"getFakeNativeURL",
"(",
"path",
"string",
")",
"string",
"{",
"u",
":=",
"*",
"c",
".",
"endpointURL",
"// Copy.",
"\n\n",
"// Override URL so that net/http will not complain.",
"u",
".",
"Scheme",
"=",
"\"",
"\"",
"\n",
... | // getFakeNativeURL returns the URL needed to make an HTTP request over a UNIX
// domain socket to the given path. | [
"getFakeNativeURL",
"returns",
"the",
"URL",
"needed",
"to",
"make",
"an",
"HTTP",
"request",
"over",
"a",
"UNIX",
"domain",
"socket",
"to",
"the",
"given",
"path",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L860-L872 | train |
ory/dockertest | docker/client.go | defaultTransport | func defaultTransport() *http.Transport {
transport := defaultPooledTransport()
transport.DisableKeepAlives = true
transport.MaxIdleConnsPerHost = -1
return transport
} | go | func defaultTransport() *http.Transport {
transport := defaultPooledTransport()
transport.DisableKeepAlives = true
transport.MaxIdleConnsPerHost = -1
return transport
} | [
"func",
"defaultTransport",
"(",
")",
"*",
"http",
".",
"Transport",
"{",
"transport",
":=",
"defaultPooledTransport",
"(",
")",
"\n",
"transport",
".",
"DisableKeepAlives",
"=",
"true",
"\n",
"transport",
".",
"MaxIdleConnsPerHost",
"=",
"-",
"1",
"\n",
"retu... | // defaultTransport returns a new http.Transport with similar default values to
// http.DefaultTransport, but with idle connections and keepalives disabled. | [
"defaultTransport",
"returns",
"a",
"new",
"http",
".",
"Transport",
"with",
"similar",
"default",
"values",
"to",
"http",
".",
"DefaultTransport",
"but",
"with",
"idle",
"connections",
"and",
"keepalives",
"disabled",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client.go#L1058-L1063 | train |
ory/dockertest | docker/env.go | Get | func (env *Env) Get(key string) (value string) {
return env.Map()[key]
} | go | func (env *Env) Get(key string) (value string) {
return env.Map()[key]
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"value",
"string",
")",
"{",
"return",
"env",
".",
"Map",
"(",
")",
"[",
"key",
"]",
"\n",
"}"
] | // Get returns the string value of the given key. | [
"Get",
"returns",
"the",
"string",
"value",
"of",
"the",
"given",
"key",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L19-L21 | train |
ory/dockertest | docker/env.go | Exists | func (env *Env) Exists(key string) bool {
_, exists := env.Map()[key]
return exists
} | go | func (env *Env) Exists(key string) bool {
_, exists := env.Map()[key]
return exists
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"Exists",
"(",
"key",
"string",
")",
"bool",
"{",
"_",
",",
"exists",
":=",
"env",
".",
"Map",
"(",
")",
"[",
"key",
"]",
"\n",
"return",
"exists",
"\n",
"}"
] | // Exists checks whether the given key is defined in the internal Env
// representation. | [
"Exists",
"checks",
"whether",
"the",
"given",
"key",
"is",
"defined",
"in",
"the",
"internal",
"Env",
"representation",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L25-L28 | train |
ory/dockertest | docker/env.go | GetBool | func (env *Env) GetBool(key string) (value bool) {
s := strings.ToLower(strings.Trim(env.Get(key), " \t"))
if s == "" || s == "0" || s == "no" || s == "false" || s == "none" {
return false
}
return true
} | go | func (env *Env) GetBool(key string) (value bool) {
s := strings.ToLower(strings.Trim(env.Get(key), " \t"))
if s == "" || s == "0" || s == "no" || s == "false" || s == "none" {
return false
}
return true
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"GetBool",
"(",
"key",
"string",
")",
"(",
"value",
"bool",
")",
"{",
"s",
":=",
"strings",
".",
"ToLower",
"(",
"strings",
".",
"Trim",
"(",
"env",
".",
"Get",
"(",
"key",
")",
",",
"\"",
"\\t",
"\"",
")",
... | // GetBool returns a boolean representation of the given key. The key is false
// whenever its value if 0, no, false, none or an empty string. Any other value
// will be interpreted as true. | [
"GetBool",
"returns",
"a",
"boolean",
"representation",
"of",
"the",
"given",
"key",
".",
"The",
"key",
"is",
"false",
"whenever",
"its",
"value",
"if",
"0",
"no",
"false",
"none",
"or",
"an",
"empty",
"string",
".",
"Any",
"other",
"value",
"will",
"be"... | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L33-L39 | train |
ory/dockertest | docker/env.go | SetBool | func (env *Env) SetBool(key string, value bool) {
if value {
env.Set(key, "1")
} else {
env.Set(key, "0")
}
} | go | func (env *Env) SetBool(key string, value bool) {
if value {
env.Set(key, "1")
} else {
env.Set(key, "0")
}
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"SetBool",
"(",
"key",
"string",
",",
"value",
"bool",
")",
"{",
"if",
"value",
"{",
"env",
".",
"Set",
"(",
"key",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"env",
".",
"Set",
"(",
"key",
",",
"\"",
... | // SetBool defines a boolean value to the given key. | [
"SetBool",
"defines",
"a",
"boolean",
"value",
"to",
"the",
"given",
"key",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L42-L48 | train |
ory/dockertest | docker/env.go | GetInt | func (env *Env) GetInt(key string) int {
return int(env.GetInt64(key))
} | go | func (env *Env) GetInt(key string) int {
return int(env.GetInt64(key))
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"GetInt",
"(",
"key",
"string",
")",
"int",
"{",
"return",
"int",
"(",
"env",
".",
"GetInt64",
"(",
"key",
")",
")",
"\n",
"}"
] | // GetInt returns the value of the provided key, converted to int.
//
// It the value cannot be represented as an integer, it returns -1. | [
"GetInt",
"returns",
"the",
"value",
"of",
"the",
"provided",
"key",
"converted",
"to",
"int",
".",
"It",
"the",
"value",
"cannot",
"be",
"represented",
"as",
"an",
"integer",
"it",
"returns",
"-",
"1",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L53-L55 | train |
ory/dockertest | docker/env.go | SetInt | func (env *Env) SetInt(key string, value int) {
env.Set(key, strconv.Itoa(value))
} | go | func (env *Env) SetInt(key string, value int) {
env.Set(key, strconv.Itoa(value))
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"SetInt",
"(",
"key",
"string",
",",
"value",
"int",
")",
"{",
"env",
".",
"Set",
"(",
"key",
",",
"strconv",
".",
"Itoa",
"(",
"value",
")",
")",
"\n",
"}"
] | // SetInt defines an integer value to the given key. | [
"SetInt",
"defines",
"an",
"integer",
"value",
"to",
"the",
"given",
"key",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L58-L60 | train |
ory/dockertest | docker/env.go | GetInt64 | func (env *Env) GetInt64(key string) int64 {
s := strings.Trim(env.Get(key), " \t")
val, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return -1
}
return val
} | go | func (env *Env) GetInt64(key string) int64 {
s := strings.Trim(env.Get(key), " \t")
val, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return -1
}
return val
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"GetInt64",
"(",
"key",
"string",
")",
"int64",
"{",
"s",
":=",
"strings",
".",
"Trim",
"(",
"env",
".",
"Get",
"(",
"key",
")",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"val",
",",
"err",
":=",
"strconv",
".",
... | // GetInt64 returns the value of the provided key, converted to int64.
//
// It the value cannot be represented as an integer, it returns -1. | [
"GetInt64",
"returns",
"the",
"value",
"of",
"the",
"provided",
"key",
"converted",
"to",
"int64",
".",
"It",
"the",
"value",
"cannot",
"be",
"represented",
"as",
"an",
"integer",
"it",
"returns",
"-",
"1",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L65-L72 | train |
ory/dockertest | docker/env.go | GetList | func (env *Env) GetList(key string) []string {
sval := env.Get(key)
if sval == "" {
return nil
}
var l []string
if err := json.Unmarshal([]byte(sval), &l); err != nil {
l = append(l, sval)
}
return l
} | go | func (env *Env) GetList(key string) []string {
sval := env.Get(key)
if sval == "" {
return nil
}
var l []string
if err := json.Unmarshal([]byte(sval), &l); err != nil {
l = append(l, sval)
}
return l
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"GetList",
"(",
"key",
"string",
")",
"[",
"]",
"string",
"{",
"sval",
":=",
"env",
".",
"Get",
"(",
"key",
")",
"\n",
"if",
"sval",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"l",
"["... | // GetList returns a list of strings matching the provided key. It handles the
// list as a JSON representation of a list of strings.
//
// If the given key matches to a single string, it will return a list
// containing only the value that matches the key. | [
"GetList",
"returns",
"a",
"list",
"of",
"strings",
"matching",
"the",
"provided",
"key",
".",
"It",
"handles",
"the",
"list",
"as",
"a",
"JSON",
"representation",
"of",
"a",
"list",
"of",
"strings",
".",
"If",
"the",
"given",
"key",
"matches",
"to",
"a"... | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L106-L116 | train |
ory/dockertest | docker/env.go | SetList | func (env *Env) SetList(key string, value []string) error {
return env.SetJSON(key, value)
} | go | func (env *Env) SetList(key string, value []string) error {
return env.SetJSON(key, value)
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"SetList",
"(",
"key",
"string",
",",
"value",
"[",
"]",
"string",
")",
"error",
"{",
"return",
"env",
".",
"SetJSON",
"(",
"key",
",",
"value",
")",
"\n",
"}"
] | // SetList stores the given list in the provided key, after serializing it to
// JSON format. | [
"SetList",
"stores",
"the",
"given",
"list",
"in",
"the",
"provided",
"key",
"after",
"serializing",
"it",
"to",
"JSON",
"format",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L120-L122 | train |
ory/dockertest | docker/env.go | Set | func (env *Env) Set(key, value string) {
*env = append(*env, key+"="+value)
} | go | func (env *Env) Set(key, value string) {
*env = append(*env, key+"="+value)
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"Set",
"(",
"key",
",",
"value",
"string",
")",
"{",
"*",
"env",
"=",
"append",
"(",
"*",
"env",
",",
"key",
"+",
"\"",
"\"",
"+",
"value",
")",
"\n",
"}"
] | // Set defines the value of a key to the given string. | [
"Set",
"defines",
"the",
"value",
"of",
"a",
"key",
"to",
"the",
"given",
"string",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/env.go#L125-L127 | train |
ory/dockertest | docker/client_windows.go | initializeNativeClient | func (c *Client) initializeNativeClient(trFunc func() *http.Transport) {
if c.endpointURL.Scheme != namedPipeProtocol {
return
}
namedPipePath := c.endpointURL.Path
dialFunc := func(network, addr string) (net.Conn, error) {
timeout := namedPipeConnectTimeout
return winio.DialPipe(namedPipePath, &timeout)
}
tr := trFunc()
tr.Dial = dialFunc
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialFunc(network, addr)
}
c.Dialer = &pipeDialer{dialFunc}
c.HTTPClient.Transport = tr
} | go | func (c *Client) initializeNativeClient(trFunc func() *http.Transport) {
if c.endpointURL.Scheme != namedPipeProtocol {
return
}
namedPipePath := c.endpointURL.Path
dialFunc := func(network, addr string) (net.Conn, error) {
timeout := namedPipeConnectTimeout
return winio.DialPipe(namedPipePath, &timeout)
}
tr := trFunc()
tr.Dial = dialFunc
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialFunc(network, addr)
}
c.Dialer = &pipeDialer{dialFunc}
c.HTTPClient.Transport = tr
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"initializeNativeClient",
"(",
"trFunc",
"func",
"(",
")",
"*",
"http",
".",
"Transport",
")",
"{",
"if",
"c",
".",
"endpointURL",
".",
"Scheme",
"!=",
"namedPipeProtocol",
"{",
"return",
"\n",
"}",
"\n",
"namedPipeP... | // initializeNativeClient initializes the native Named Pipe client for Windows | [
"initializeNativeClient",
"initializes",
"the",
"native",
"Named",
"Pipe",
"client",
"for",
"Windows"
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/client_windows.go#L29-L45 | train |
ory/dockertest | docker/auth.go | NewAuthConfigurationsFromFile | func NewAuthConfigurationsFromFile(path string) (*AuthConfigurations, error) {
r, err := os.Open(path)
if err != nil {
return nil, err
}
return NewAuthConfigurations(r)
} | go | func NewAuthConfigurationsFromFile(path string) (*AuthConfigurations, error) {
r, err := os.Open(path)
if err != nil {
return nil, err
}
return NewAuthConfigurations(r)
} | [
"func",
"NewAuthConfigurationsFromFile",
"(",
"path",
"string",
")",
"(",
"*",
"AuthConfigurations",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
... | // NewAuthConfigurationsFromFile returns AuthConfigurations from a path containing JSON
// in the same format as the .dockercfg file. | [
"NewAuthConfigurationsFromFile",
"returns",
"AuthConfigurations",
"from",
"a",
"path",
"containing",
"JSON",
"in",
"the",
"same",
"format",
"as",
"the",
".",
"dockercfg",
"file",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/auth.go#L51-L57 | train |
ory/dockertest | docker/auth.go | authConfigs | func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) {
c := &AuthConfigurations{
Configs: make(map[string]AuthConfiguration),
}
for reg, conf := range confs {
if conf.Auth == "" {
continue
}
data, err := base64.StdEncoding.DecodeString(conf.Auth)
if err != nil {
return nil, err
}
userpass := strings.SplitN(string(data), ":", 2)
if len(userpass) != 2 {
return nil, ErrCannotParseDockercfg
}
c.Configs[reg] = AuthConfiguration{
Email: conf.Email,
Username: userpass[0],
Password: userpass[1],
ServerAddress: reg,
}
}
return c, nil
} | go | func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) {
c := &AuthConfigurations{
Configs: make(map[string]AuthConfiguration),
}
for reg, conf := range confs {
if conf.Auth == "" {
continue
}
data, err := base64.StdEncoding.DecodeString(conf.Auth)
if err != nil {
return nil, err
}
userpass := strings.SplitN(string(data), ":", 2)
if len(userpass) != 2 {
return nil, ErrCannotParseDockercfg
}
c.Configs[reg] = AuthConfiguration{
Email: conf.Email,
Username: userpass[0],
Password: userpass[1],
ServerAddress: reg,
}
}
return c, nil
} | [
"func",
"authConfigs",
"(",
"confs",
"map",
"[",
"string",
"]",
"dockerConfig",
")",
"(",
"*",
"AuthConfigurations",
",",
"error",
")",
"{",
"c",
":=",
"&",
"AuthConfigurations",
"{",
"Configs",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"AuthConfigurati... | // authConfigs converts a dockerConfigs map to a AuthConfigurations object. | [
"authConfigs",
"converts",
"a",
"dockerConfigs",
"map",
"to",
"a",
"AuthConfigurations",
"object",
"."
] | 56b367fe94ad17019ab80b91fe686218e65ce9fa | https://github.com/ory/dockertest/blob/56b367fe94ad17019ab80b91fe686218e65ce9fa/docker/auth.go#L127-L151 | train |
hyperhq/hyperd | server/server_unix.go | newServer | func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
var (
err error
ls []net.Listener
)
switch proto {
case "fd":
ls, err = listenFD(addr, s.cfg.TLSConfig)
if err != nil {
return nil, err
}
case "tcp":
l, err := s.initTCPSocket(addr)
if err != nil {
return nil, err
}
ls = append(ls, l)
case "unix":
l, err := sockets.NewUnixSocket(addr, s.cfg.SocketGroup)
if err != nil {
return nil, fmt.Errorf("can't create unix socket %s: %v", addr, err)
}
ls = append(ls, l)
default:
return nil, fmt.Errorf("Invalid protocol format: %q", proto)
}
var res []*HTTPServer
for _, l := range ls {
res = append(res, &HTTPServer{
&http.Server{
Addr: addr,
},
l,
})
}
return res, nil
} | go | func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
var (
err error
ls []net.Listener
)
switch proto {
case "fd":
ls, err = listenFD(addr, s.cfg.TLSConfig)
if err != nil {
return nil, err
}
case "tcp":
l, err := s.initTCPSocket(addr)
if err != nil {
return nil, err
}
ls = append(ls, l)
case "unix":
l, err := sockets.NewUnixSocket(addr, s.cfg.SocketGroup)
if err != nil {
return nil, fmt.Errorf("can't create unix socket %s: %v", addr, err)
}
ls = append(ls, l)
default:
return nil, fmt.Errorf("Invalid protocol format: %q", proto)
}
var res []*HTTPServer
for _, l := range ls {
res = append(res, &HTTPServer{
&http.Server{
Addr: addr,
},
l,
})
}
return res, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"newServer",
"(",
"proto",
",",
"addr",
"string",
")",
"(",
"[",
"]",
"*",
"HTTPServer",
",",
"error",
")",
"{",
"var",
"(",
"err",
"error",
"\n",
"ls",
"[",
"]",
"net",
".",
"Listener",
"\n",
")",
"\n",
"s... | // newServer sets up the required HTTPServers and does protocol specific checking.
// newServer does not set any muxers, you should set it later to Handler field | [
"newServer",
"sets",
"up",
"the",
"required",
"HTTPServers",
"and",
"does",
"protocol",
"specific",
"checking",
".",
"newServer",
"does",
"not",
"set",
"any",
"muxers",
"you",
"should",
"set",
"it",
"later",
"to",
"Handler",
"field"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/server_unix.go#L20-L56 | train |
hyperhq/hyperd | daemon/pod/servicediscovery.go | add | func (s *Services) add(newServs []*apitypes.UserService) error {
var err error
// check if adding service conflict with existing ones
exist := make(map[serviceKey]bool, s.size())
for _, srv := range s.spec {
exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
}
for _, srv := range newServs {
if exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] {
err = fmt.Errorf("service %v conflicts with existing ones", newServs)
s.Log(ERROR, err)
return err
}
exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
}
// if pod is running, convert service to patch and send to vm
if s.p.IsRunning() {
if err = s.commit(newServs, "add"); err != nil {
return err
}
}
s.spec = append(s.spec, newServs...)
return nil
} | go | func (s *Services) add(newServs []*apitypes.UserService) error {
var err error
// check if adding service conflict with existing ones
exist := make(map[serviceKey]bool, s.size())
for _, srv := range s.spec {
exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
}
for _, srv := range newServs {
if exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] {
err = fmt.Errorf("service %v conflicts with existing ones", newServs)
s.Log(ERROR, err)
return err
}
exist[serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}] = true
}
// if pod is running, convert service to patch and send to vm
if s.p.IsRunning() {
if err = s.commit(newServs, "add"); err != nil {
return err
}
}
s.spec = append(s.spec, newServs...)
return nil
} | [
"func",
"(",
"s",
"*",
"Services",
")",
"add",
"(",
"newServs",
"[",
"]",
"*",
"apitypes",
".",
"UserService",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"// check if adding service conflict with existing ones",
"exist",
":=",
"make",
"(",
"map",
"[",
"... | // add will only add services in list that don't exist, else failed | [
"add",
"will",
"only",
"add",
"services",
"in",
"list",
"that",
"don",
"t",
"exist",
"else",
"failed"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/servicediscovery.go#L88-L113 | train |
hyperhq/hyperd | daemon/pod/servicediscovery.go | update | func (s *Services) update(srvs []*apitypes.UserService) error {
var err error
// check if update service list conflicts
tbd := make(map[serviceKey]bool, len(srvs))
for _, srv := range srvs {
key := serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}
if tbd[key] {
err = fmt.Errorf("given service list conflict: %v", srv)
s.Log(ERROR, err)
return err
}
tbd[key] = true
}
if s.p.IsRunning() {
if err = s.commit(srvs, "update"); err != nil {
return err
}
}
s.spec = srvs
return nil
} | go | func (s *Services) update(srvs []*apitypes.UserService) error {
var err error
// check if update service list conflicts
tbd := make(map[serviceKey]bool, len(srvs))
for _, srv := range srvs {
key := serviceKey{srv.ServiceIP, srv.ServicePort, srv.Protocol}
if tbd[key] {
err = fmt.Errorf("given service list conflict: %v", srv)
s.Log(ERROR, err)
return err
}
tbd[key] = true
}
if s.p.IsRunning() {
if err = s.commit(srvs, "update"); err != nil {
return err
}
}
s.spec = srvs
return nil
} | [
"func",
"(",
"s",
"*",
"Services",
")",
"update",
"(",
"srvs",
"[",
"]",
"*",
"apitypes",
".",
"UserService",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"// check if update service list conflicts",
"tbd",
":=",
"make",
"(",
"map",
"[",
"serviceKey",
"... | // update removes services in list that already exist, and add with new ones
// or just add new ones if they are not exist already | [
"update",
"removes",
"services",
"in",
"list",
"that",
"already",
"exist",
"and",
"add",
"with",
"new",
"ones",
"or",
"just",
"add",
"new",
"ones",
"if",
"they",
"are",
"not",
"exist",
"already"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/servicediscovery.go#L144-L166 | train |
hyperhq/hyperd | daemon/server.go | CmdListPortMappings | func (daemon *Daemon) CmdListPortMappings(podId string) (*engine.Env, error) {
p, ok := daemon.PodList.Get(podId)
if !ok {
return nil, errors.ErrPodNotFound.WithArgs(podId)
}
pms := p.ListPortMappings()
v := &engine.Env{}
v.SetJson("portMappings", pms)
return v, nil
} | go | func (daemon *Daemon) CmdListPortMappings(podId string) (*engine.Env, error) {
p, ok := daemon.PodList.Get(podId)
if !ok {
return nil, errors.ErrPodNotFound.WithArgs(podId)
}
pms := p.ListPortMappings()
v := &engine.Env{}
v.SetJson("portMappings", pms)
return v, nil
} | [
"func",
"(",
"daemon",
"*",
"Daemon",
")",
"CmdListPortMappings",
"(",
"podId",
"string",
")",
"(",
"*",
"engine",
".",
"Env",
",",
"error",
")",
"{",
"p",
",",
"ok",
":=",
"daemon",
".",
"PodList",
".",
"Get",
"(",
"podId",
")",
"\n",
"if",
"!",
... | // pod level port mappings API | [
"pod",
"level",
"port",
"mappings",
"API"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/server.go#L306-L317 | train |
hyperhq/hyperd | serverrpc/exec.go | ExecSignal | func (s *ServerRPC) ExecSignal(ctx context.Context, req *types.ExecSignalRequest) (*types.ExecSignalResponse, error) {
err := s.daemon.KillExec(req.ContainerID, req.ExecID, req.Signal)
if err != nil {
return nil, err
}
return &types.ExecSignalResponse{}, nil
} | go | func (s *ServerRPC) ExecSignal(ctx context.Context, req *types.ExecSignalRequest) (*types.ExecSignalResponse, error) {
err := s.daemon.KillExec(req.ContainerID, req.ExecID, req.Signal)
if err != nil {
return nil, err
}
return &types.ExecSignalResponse{}, nil
} | [
"func",
"(",
"s",
"*",
"ServerRPC",
")",
"ExecSignal",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"types",
".",
"ExecSignalRequest",
")",
"(",
"*",
"types",
".",
"ExecSignalResponse",
",",
"error",
")",
"{",
"err",
":=",
"s",
".",
"daemon"... | // ExecSignal sends a singal to specified exec of specified container | [
"ExecSignal",
"sends",
"a",
"singal",
"to",
"specified",
"exec",
"of",
"specified",
"container"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/serverrpc/exec.go#L104-L111 | train |
hyperhq/hyperd | client/build.go | ValidateContextDirectory | func ValidateContextDirectory(srcPath string, excludes []string) error {
contextRoot := filepath.Join(srcPath, ".")
return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
// skip this directory/file if it's not in the path, it won't get added to the context
if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
return err
} else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
return err
} else if skip {
if f.IsDir() {
return filepath.SkipDir
}
return nil
}
if err != nil {
if os.IsPermission(err) {
return fmt.Errorf("can't stat '%s'", filePath)
}
if os.IsNotExist(err) {
return nil
}
return err
}
// skip checking if symlinks point to non-existing files, such symlinks can be useful
// also skip named pipes, because they hanging on open
if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
return nil
}
if !f.IsDir() {
currentFile, err := os.Open(filePath)
if err != nil && os.IsPermission(err) {
return fmt.Errorf("no permission to read from '%s'", filePath)
}
currentFile.Close()
}
return nil
})
} | go | func ValidateContextDirectory(srcPath string, excludes []string) error {
contextRoot := filepath.Join(srcPath, ".")
return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
// skip this directory/file if it's not in the path, it won't get added to the context
if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
return err
} else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
return err
} else if skip {
if f.IsDir() {
return filepath.SkipDir
}
return nil
}
if err != nil {
if os.IsPermission(err) {
return fmt.Errorf("can't stat '%s'", filePath)
}
if os.IsNotExist(err) {
return nil
}
return err
}
// skip checking if symlinks point to non-existing files, such symlinks can be useful
// also skip named pipes, because they hanging on open
if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
return nil
}
if !f.IsDir() {
currentFile, err := os.Open(filePath)
if err != nil && os.IsPermission(err) {
return fmt.Errorf("no permission to read from '%s'", filePath)
}
currentFile.Close()
}
return nil
})
} | [
"func",
"ValidateContextDirectory",
"(",
"srcPath",
"string",
",",
"excludes",
"[",
"]",
"string",
")",
"error",
"{",
"contextRoot",
":=",
"filepath",
".",
"Join",
"(",
"srcPath",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"filepath",
".",
"Walk",
"(",
"conte... | // validateContextDirectory checks if all the contents of the directory
// can be read and returns an error if some files can't be read
// symlinks which point to non-existing files don't trigger an error | [
"validateContextDirectory",
"checks",
"if",
"all",
"the",
"contents",
"of",
"the",
"directory",
"can",
"be",
"read",
"and",
"returns",
"an",
"error",
"if",
"some",
"files",
"can",
"t",
"be",
"read",
"symlinks",
"which",
"point",
"to",
"non",
"-",
"existing",... | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/client/build.go#L177-L218 | train |
hyperhq/hyperd | server/server.go | InitRouters | func (s *Server) InitRouters(d *daemon.Daemon) {
s.addRouter(container.NewRouter(d))
s.addRouter(pod.NewRouter(d))
s.addRouter(service.NewRouter(d))
s.addRouter(local.NewRouter(d))
s.addRouter(system.NewRouter(d))
s.addRouter(build.NewRouter(d))
} | go | func (s *Server) InitRouters(d *daemon.Daemon) {
s.addRouter(container.NewRouter(d))
s.addRouter(pod.NewRouter(d))
s.addRouter(service.NewRouter(d))
s.addRouter(local.NewRouter(d))
s.addRouter(system.NewRouter(d))
s.addRouter(build.NewRouter(d))
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"InitRouters",
"(",
"d",
"*",
"daemon",
".",
"Daemon",
")",
"{",
"s",
".",
"addRouter",
"(",
"container",
".",
"NewRouter",
"(",
"d",
")",
")",
"\n",
"s",
".",
"addRouter",
"(",
"pod",
".",
"NewRouter",
"(",
... | // InitRouters initializes a list of routers for the server. | [
"InitRouters",
"initializes",
"a",
"list",
"of",
"routers",
"for",
"the",
"server",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/server.go#L177-L184 | train |
hyperhq/hyperd | server/server.go | addRouter | func (s *Server) addRouter(r router.Router) {
s.routers = append(s.routers, r)
} | go | func (s *Server) addRouter(r router.Router) {
s.routers = append(s.routers, r)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"addRouter",
"(",
"r",
"router",
".",
"Router",
")",
"{",
"s",
".",
"routers",
"=",
"append",
"(",
"s",
".",
"routers",
",",
"r",
")",
"\n",
"}"
] | // addRouter adds a new router to the server. | [
"addRouter",
"adds",
"a",
"new",
"router",
"to",
"the",
"server",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/server.go#L187-L189 | train |
hyperhq/hyperd | server/server.go | createMux | func (s *Server) createMux() *mux.Router {
m := mux.NewRouter()
if utils.IsDebugEnabled() {
profilerSetup(m, "/debug/")
}
glog.V(3).Infof("Registering routers")
for _, apiRouter := range s.routers {
for _, r := range apiRouter.Routes() {
f := s.makeHTTPHandler(r.Handler())
glog.V(3).Infof("Registering %s, %s", r.Method(), r.Path())
m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
m.Path(r.Path()).Methods(r.Method()).Handler(f)
}
}
return m
} | go | func (s *Server) createMux() *mux.Router {
m := mux.NewRouter()
if utils.IsDebugEnabled() {
profilerSetup(m, "/debug/")
}
glog.V(3).Infof("Registering routers")
for _, apiRouter := range s.routers {
for _, r := range apiRouter.Routes() {
f := s.makeHTTPHandler(r.Handler())
glog.V(3).Infof("Registering %s, %s", r.Method(), r.Path())
m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
m.Path(r.Path()).Methods(r.Method()).Handler(f)
}
}
return m
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"createMux",
"(",
")",
"*",
"mux",
".",
"Router",
"{",
"m",
":=",
"mux",
".",
"NewRouter",
"(",
")",
"\n",
"if",
"utils",
".",
"IsDebugEnabled",
"(",
")",
"{",
"profilerSetup",
"(",
"m",
",",
"\"",
"\"",
")",... | // createMux initializes the main router the server uses.
// we keep enableCors just for legacy usage, need to be removed in the future | [
"createMux",
"initializes",
"the",
"main",
"router",
"the",
"server",
"uses",
".",
"we",
"keep",
"enableCors",
"just",
"for",
"legacy",
"usage",
"need",
"to",
"be",
"removed",
"in",
"the",
"future"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/server.go#L193-L211 | train |
hyperhq/hyperd | server/server.go | Wait | func (s *Server) Wait(waitChan chan error) {
if err := s.serveAPI(); err != nil {
glog.Errorf("ServeAPI error: %v", err)
waitChan <- err
return
}
waitChan <- nil
} | go | func (s *Server) Wait(waitChan chan error) {
if err := s.serveAPI(); err != nil {
glog.Errorf("ServeAPI error: %v", err)
waitChan <- err
return
}
waitChan <- nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Wait",
"(",
"waitChan",
"chan",
"error",
")",
"{",
"if",
"err",
":=",
"s",
".",
"serveAPI",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"glog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"waitChan"... | // Wait blocks the server goroutine until it exits.
// It sends an error message if there is any error during
// the API execution. | [
"Wait",
"blocks",
"the",
"server",
"goroutine",
"until",
"it",
"exits",
".",
"It",
"sends",
"an",
"error",
"message",
"if",
"there",
"is",
"any",
"error",
"during",
"the",
"API",
"execution",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/server.go#L216-L223 | train |
hyperhq/hyperd | daemon/pod/etchosts.go | prepareHosts | func prepareHosts(podID string) (string, error) {
var err error
hostsDir, hostsPath := HostsPath(podID)
if err = os.MkdirAll(hostsDir, 0755); err != nil {
return "", err
}
if _, err = os.Stat(hostsPath); err != nil && os.IsNotExist(err) {
// mount tmpfs on hostsDir
if err := syscall.Mount(podID+"-hosts", hostsDir, "tmpfs", 0, "size=1024K"); err != nil {
return "", err
}
hostsContent, err := generateDefaultHosts()
if err != nil {
return "", err
}
return hostsPath, ioutil.WriteFile(hostsPath, hostsContent, 0644)
}
return hostsPath, nil
} | go | func prepareHosts(podID string) (string, error) {
var err error
hostsDir, hostsPath := HostsPath(podID)
if err = os.MkdirAll(hostsDir, 0755); err != nil {
return "", err
}
if _, err = os.Stat(hostsPath); err != nil && os.IsNotExist(err) {
// mount tmpfs on hostsDir
if err := syscall.Mount(podID+"-hosts", hostsDir, "tmpfs", 0, "size=1024K"); err != nil {
return "", err
}
hostsContent, err := generateDefaultHosts()
if err != nil {
return "", err
}
return hostsPath, ioutil.WriteFile(hostsPath, hostsContent, 0644)
}
return hostsPath, nil
} | [
"func",
"prepareHosts",
"(",
"podID",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"hostsDir",
",",
"hostsPath",
":=",
"HostsPath",
"(",
"podID",
")",
"\n\n",
"if",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"hostsD... | // prepareHosts creates hosts file for given pod | [
"prepareHosts",
"creates",
"hosts",
"file",
"for",
"given",
"pod"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/etchosts.go#L68-L91 | train |
hyperhq/hyperd | networking/portmapping/host_portmapping_linux.go | NewPortRange | func NewPortRange(r string) (*PortRange, error) {
segs := strings.SplitN(r, "-", 2)
b, err := strconv.ParseUint(segs[0], 10, 16)
if err != nil {
return nil, err
}
e := b
if len(segs) > 1 {
e, err = strconv.ParseUint(segs[1], 10, 16)
if err != nil {
return nil, err
}
}
return &PortRange{
Begin: int(b),
End: int(e),
}, nil
} | go | func NewPortRange(r string) (*PortRange, error) {
segs := strings.SplitN(r, "-", 2)
b, err := strconv.ParseUint(segs[0], 10, 16)
if err != nil {
return nil, err
}
e := b
if len(segs) > 1 {
e, err = strconv.ParseUint(segs[1], 10, 16)
if err != nil {
return nil, err
}
}
return &PortRange{
Begin: int(b),
End: int(e),
}, nil
} | [
"func",
"NewPortRange",
"(",
"r",
"string",
")",
"(",
"*",
"PortRange",
",",
"error",
")",
"{",
"segs",
":=",
"strings",
".",
"SplitN",
"(",
"r",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"b",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"segs... | // NewPortRange generate a port range from string r. the r should be a decimal number or
// in format begin-end, where begin and end are both decimal number. And the port range should
// be 0-65535, i.e. 16-bit unsigned int
// It returns PortRange pointer for valid input, otherwise return error | [
"NewPortRange",
"generate",
"a",
"port",
"range",
"from",
"string",
"r",
".",
"the",
"r",
"should",
"be",
"a",
"decimal",
"number",
"or",
"in",
"format",
"begin",
"-",
"end",
"where",
"begin",
"and",
"end",
"are",
"both",
"decimal",
"number",
".",
"And",... | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/networking/portmapping/host_portmapping_linux.go#L33-L50 | train |
hyperhq/hyperd | networking/portmapping/setup_linux.go | Setup | func Setup(bIface, addr string, disable bool) error {
var err error
disableIptables = disable
bridgeIface = bIface
if disableIptables {
hlog.Log(hlog.DEBUG, "Iptables is disabled")
return nil
}
hlog.Log(hlog.TRACE, "setting up iptables")
err = setupIPTables(addr)
if err != nil {
hlog.Log(hlog.ERROR, "failed to setup iptables: %v", err)
return err
}
return nil
} | go | func Setup(bIface, addr string, disable bool) error {
var err error
disableIptables = disable
bridgeIface = bIface
if disableIptables {
hlog.Log(hlog.DEBUG, "Iptables is disabled")
return nil
}
hlog.Log(hlog.TRACE, "setting up iptables")
err = setupIPTables(addr)
if err != nil {
hlog.Log(hlog.ERROR, "failed to setup iptables: %v", err)
return err
}
return nil
} | [
"func",
"Setup",
"(",
"bIface",
",",
"addr",
"string",
",",
"disable",
"bool",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"disableIptables",
"=",
"disable",
"\n",
"bridgeIface",
"=",
"bIface",
"\n\n",
"if",
"disableIptables",
"{",
"hlog",
".",
"Log"... | //setup environment for iptables and IP forwarding | [
"setup",
"environment",
"for",
"iptables",
"and",
"IP",
"forwarding"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/networking/portmapping/setup_linux.go#L18-L37 | train |
hyperhq/hyperd | networking/portmapping/iptables/iptables_linux.go | OperatePortMap | func OperatePortMap(action Action, chain string, rule []string) error {
if output, err := Raw(append([]string{
"-t", string(Nat), string(action), chain}, rule...)...); err != nil {
return fmt.Errorf("Unable to setup network port map: %s", err)
} else if len(output) != 0 {
return &ChainError{Chain: chain, Output: output}
}
return nil
} | go | func OperatePortMap(action Action, chain string, rule []string) error {
if output, err := Raw(append([]string{
"-t", string(Nat), string(action), chain}, rule...)...); err != nil {
return fmt.Errorf("Unable to setup network port map: %s", err)
} else if len(output) != 0 {
return &ChainError{Chain: chain, Output: output}
}
return nil
} | [
"func",
"OperatePortMap",
"(",
"action",
"Action",
",",
"chain",
"string",
",",
"rule",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"output",
",",
"err",
":=",
"Raw",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"string",
"(",
"Na... | // Check if a dnat rule exists | [
"Check",
"if",
"a",
"dnat",
"rule",
"exists"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/networking/portmapping/iptables/iptables_linux.go#L62-L71 | train |
hyperhq/hyperd | networking/portmapping/iptables/iptables_linux.go | Exists | func Exists(table Table, chain string, rule ...string) bool {
if string(table) == "" {
table = Filter
}
// iptables -C, --check option was added in v.1.4.11
// http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
// try -C
// if exit status is 0 then return true, the rule exists
if _, err := Raw(append([]string{
"-t", string(table), "-C", chain}, rule...)...); err == nil {
return true
}
// parse "iptables -S" for the rule (this checks rules in a specific chain
// in a specific table)
ruleString := strings.Join(rule, " ")
existingRules, _ := exec.Command("iptables", "-t", string(table), "-S", chain).Output()
// regex to replace ips in rule
// because MASQUERADE rule will not be exactly what was passed
re := regexp.MustCompile(`[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}`)
return strings.Contains(
re.ReplaceAllString(string(existingRules), "?"),
re.ReplaceAllString(ruleString, "?"),
)
} | go | func Exists(table Table, chain string, rule ...string) bool {
if string(table) == "" {
table = Filter
}
// iptables -C, --check option was added in v.1.4.11
// http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
// try -C
// if exit status is 0 then return true, the rule exists
if _, err := Raw(append([]string{
"-t", string(table), "-C", chain}, rule...)...); err == nil {
return true
}
// parse "iptables -S" for the rule (this checks rules in a specific chain
// in a specific table)
ruleString := strings.Join(rule, " ")
existingRules, _ := exec.Command("iptables", "-t", string(table), "-S", chain).Output()
// regex to replace ips in rule
// because MASQUERADE rule will not be exactly what was passed
re := regexp.MustCompile(`[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}`)
return strings.Contains(
re.ReplaceAllString(string(existingRules), "?"),
re.ReplaceAllString(ruleString, "?"),
)
} | [
"func",
"Exists",
"(",
"table",
"Table",
",",
"chain",
"string",
",",
"rule",
"...",
"string",
")",
"bool",
"{",
"if",
"string",
"(",
"table",
")",
"==",
"\"",
"\"",
"{",
"table",
"=",
"Filter",
"\n",
"}",
"\n\n",
"// iptables -C, --check option was added ... | // Check if a rule exists | [
"Check",
"if",
"a",
"rule",
"exists"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/networking/portmapping/iptables/iptables_linux.go#L142-L170 | train |
hyperhq/hyperd | networking/portmapping/iptables/iptables_linux.go | Raw | func Raw(args ...string) ([]byte, error) {
if err := initCheck(); err != nil {
return nil, err
}
if supportsXlock {
args = append([]string{"--wait"}, args...)
}
hlog.Log(hlog.TRACE, "%s, %v", iptablesPath, args)
output, err := exec.Command(iptablesPath, args...).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
}
// ignore iptables' message about xtables lock
if strings.Contains(string(output), "waiting for it to exit") {
output = []byte("")
}
return output, err
} | go | func Raw(args ...string) ([]byte, error) {
if err := initCheck(); err != nil {
return nil, err
}
if supportsXlock {
args = append([]string{"--wait"}, args...)
}
hlog.Log(hlog.TRACE, "%s, %v", iptablesPath, args)
output, err := exec.Command(iptablesPath, args...).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
}
// ignore iptables' message about xtables lock
if strings.Contains(string(output), "waiting for it to exit") {
output = []byte("")
}
return output, err
} | [
"func",
"Raw",
"(",
"args",
"...",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"err",
":=",
"initCheck",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"supportsXlock",
"{",
"... | // Call 'iptables' system command, passing supplied arguments | [
"Call",
"iptables",
"system",
"command",
"passing",
"supplied",
"arguments"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/networking/portmapping/iptables/iptables_linux.go#L173-L194 | train |
hyperhq/hyperd | daemon/daemondb/daemondb.go | LagecyGetPod | func (d *DaemonDB) LagecyGetPod(id string) ([]byte, error) {
return d.Get(keyPod(id))
} | go | func (d *DaemonDB) LagecyGetPod(id string) ([]byte, error) {
return d.Get(keyPod(id))
} | [
"func",
"(",
"d",
"*",
"DaemonDB",
")",
"LagecyGetPod",
"(",
"id",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"d",
".",
"Get",
"(",
"keyPod",
"(",
"id",
")",
")",
"\n",
"}"
] | // Pods podId and args | [
"Pods",
"podId",
"and",
"args"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/daemondb/daemondb.go#L43-L45 | train |
hyperhq/hyperd | engine/env.go | Get | func (env *Env) Get(key string) (value string) {
// not using Map() because of the extra allocations https://github.com/docker/docker/pull/7488#issuecomment-51638315
for _, kv := range *env {
if strings.Index(kv, "=") == -1 {
continue
}
parts := strings.SplitN(kv, "=", 2)
if parts[0] != key {
continue
}
if len(parts) < 2 {
value = ""
} else {
value = parts[1]
}
}
return
} | go | func (env *Env) Get(key string) (value string) {
// not using Map() because of the extra allocations https://github.com/docker/docker/pull/7488#issuecomment-51638315
for _, kv := range *env {
if strings.Index(kv, "=") == -1 {
continue
}
parts := strings.SplitN(kv, "=", 2)
if parts[0] != key {
continue
}
if len(parts) < 2 {
value = ""
} else {
value = parts[1]
}
}
return
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"value",
"string",
")",
"{",
"// not using Map() because of the extra allocations https://github.com/docker/docker/pull/7488#issuecomment-51638315",
"for",
"_",
",",
"kv",
":=",
"range",
"*",
... | // Get returns the last value associated with the given key. If there are no
// values associated with the key, Get returns the empty string. | [
"Get",
"returns",
"the",
"last",
"value",
"associated",
"with",
"the",
"given",
"key",
".",
"If",
"there",
"are",
"no",
"values",
"associated",
"with",
"the",
"key",
"Get",
"returns",
"the",
"empty",
"string",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/engine/env.go#L18-L35 | train |
hyperhq/hyperd | engine/env.go | Decode | func (env *Env) Decode(src io.Reader) error {
m := make(map[string]interface{})
d := json.NewDecoder(src)
// We need this or we'll lose data when we decode int64 in json
d.UseNumber()
if err := d.Decode(&m); err != nil {
return err
}
for k, v := range m {
env.SetAuto(k, v)
}
return nil
} | go | func (env *Env) Decode(src io.Reader) error {
m := make(map[string]interface{})
d := json.NewDecoder(src)
// We need this or we'll lose data when we decode int64 in json
d.UseNumber()
if err := d.Decode(&m); err != nil {
return err
}
for k, v := range m {
env.SetAuto(k, v)
}
return nil
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"Decode",
"(",
"src",
"io",
".",
"Reader",
")",
"error",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"d",
":=",
"json",
".",
"NewDecoder",
"(",
"src",
")",
"\n",... | // DecodeEnv decodes `src` as a json dictionary, and adds
// each decoded key-value pair to the environment.
//
// If `src` cannot be decoded as a json dictionary, an error
// is returned. | [
"DecodeEnv",
"decodes",
"src",
"as",
"a",
"json",
"dictionary",
"and",
"adds",
"each",
"decoded",
"key",
"-",
"value",
"pair",
"to",
"the",
"environment",
".",
"If",
"src",
"cannot",
"be",
"decoded",
"as",
"a",
"json",
"dictionary",
"an",
"error",
"is",
... | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/engine/env.go#L189-L201 | train |
hyperhq/hyperd | engine/env.go | MultiMap | func (env *Env) MultiMap() map[string][]string {
m := make(map[string][]string)
for _, kv := range *env {
parts := strings.SplitN(kv, "=", 2)
m[parts[0]] = append(m[parts[0]], parts[1])
}
return m
} | go | func (env *Env) MultiMap() map[string][]string {
m := make(map[string][]string)
for _, kv := range *env {
parts := strings.SplitN(kv, "=", 2)
m[parts[0]] = append(m[parts[0]], parts[1])
}
return m
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"MultiMap",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"kv",
":=",
"range",
"*",
"env",... | // MultiMap returns a representation of env as a
// map of string arrays, keyed by string.
// This is the same structure as http headers for example,
// which allow each key to have multiple values. | [
"MultiMap",
"returns",
"a",
"representation",
"of",
"env",
"as",
"a",
"map",
"of",
"string",
"arrays",
"keyed",
"by",
"string",
".",
"This",
"is",
"the",
"same",
"structure",
"as",
"http",
"headers",
"for",
"example",
"which",
"allow",
"each",
"key",
"to",... | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/engine/env.go#L294-L301 | train |
hyperhq/hyperd | engine/env.go | InitMultiMap | func (env *Env) InitMultiMap(m map[string][]string) {
(*env) = make([]string, 0, len(m))
for k, vals := range m {
for _, v := range vals {
env.Set(k, v)
}
}
} | go | func (env *Env) InitMultiMap(m map[string][]string) {
(*env) = make([]string, 0, len(m))
for k, vals := range m {
for _, v := range vals {
env.Set(k, v)
}
}
} | [
"func",
"(",
"env",
"*",
"Env",
")",
"InitMultiMap",
"(",
"m",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"{",
"(",
"*",
"env",
")",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
... | // InitMultiMap removes all values in env, then initializes
// new values from the contents of m. | [
"InitMultiMap",
"removes",
"all",
"values",
"in",
"env",
"then",
"initializes",
"new",
"values",
"from",
"the",
"contents",
"of",
"m",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/engine/env.go#L305-L312 | train |
hyperhq/hyperd | lib/goconfig/conf.go | SetValue | func (c *ConfigFile) SetValue(section, key, value string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if len(key) == 0 {
return false
}
if c.BlockMode {
c.lock.Lock()
defer c.lock.Unlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
// Execute add operation.
c.data[section] = make(map[string]string)
// Append section to list.
c.sectionList = append(c.sectionList, section)
}
// Check if key exists.
_, ok := c.data[section][key]
c.data[section][key] = value
if !ok {
// If not exists, append to key list.
c.keyList[section] = append(c.keyList[section], key)
}
return !ok
} | go | func (c *ConfigFile) SetValue(section, key, value string) bool {
// Blank section name represents DEFAULT section.
if len(section) == 0 {
section = DEFAULT_SECTION
}
if len(key) == 0 {
return false
}
if c.BlockMode {
c.lock.Lock()
defer c.lock.Unlock()
}
// Check if section exists.
if _, ok := c.data[section]; !ok {
// Execute add operation.
c.data[section] = make(map[string]string)
// Append section to list.
c.sectionList = append(c.sectionList, section)
}
// Check if key exists.
_, ok := c.data[section][key]
c.data[section][key] = value
if !ok {
// If not exists, append to key list.
c.keyList[section] = append(c.keyList[section], key)
}
return !ok
} | [
"func",
"(",
"c",
"*",
"ConfigFile",
")",
"SetValue",
"(",
"section",
",",
"key",
",",
"value",
"string",
")",
"bool",
"{",
"// Blank section name represents DEFAULT section.",
"if",
"len",
"(",
"section",
")",
"==",
"0",
"{",
"section",
"=",
"DEFAULT_SECTION"... | // SetValue adds a new section-key-value to the configuration.
// It returns true if the key and value were inserted,
// or returns false if the value was overwritten.
// If the section does not exist in advance, it will be created. | [
"SetValue",
"adds",
"a",
"new",
"section",
"-",
"key",
"-",
"value",
"to",
"the",
"configuration",
".",
"It",
"returns",
"true",
"if",
"the",
"key",
"and",
"value",
"were",
"inserted",
"or",
"returns",
"false",
"if",
"the",
"value",
"was",
"overwritten",
... | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/lib/goconfig/conf.go#L85-L115 | train |
hyperhq/hyperd | daemon/pod/streams.go | NewStreamConfig | func NewStreamConfig() *StreamConfig {
return &StreamConfig{
stderr: new(broadcaster.Unbuffered),
stdout: new(broadcaster.Unbuffered),
}
} | go | func NewStreamConfig() *StreamConfig {
return &StreamConfig{
stderr: new(broadcaster.Unbuffered),
stdout: new(broadcaster.Unbuffered),
}
} | [
"func",
"NewStreamConfig",
"(",
")",
"*",
"StreamConfig",
"{",
"return",
"&",
"StreamConfig",
"{",
"stderr",
":",
"new",
"(",
"broadcaster",
".",
"Unbuffered",
")",
",",
"stdout",
":",
"new",
"(",
"broadcaster",
".",
"Unbuffered",
")",
",",
"}",
"\n",
"}... | // NewStreamConfig creates a stream config and initializes
// the standard err and standard out to new unbuffered broadcasters. | [
"NewStreamConfig",
"creates",
"a",
"stream",
"config",
"and",
"initializes",
"the",
"standard",
"err",
"and",
"standard",
"out",
"to",
"new",
"unbuffered",
"broadcasters",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/streams.go#L39-L44 | train |
hyperhq/hyperd | daemon/pod/streams.go | StdoutPipe | func (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser {
bytesPipe := ioutils.NewBytesPipe(nil)
streamConfig.stdout.Add(bytesPipe)
return bytesPipe
} | go | func (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser {
bytesPipe := ioutils.NewBytesPipe(nil)
streamConfig.stdout.Add(bytesPipe)
return bytesPipe
} | [
"func",
"(",
"streamConfig",
"*",
"StreamConfig",
")",
"StdoutPipe",
"(",
")",
"io",
".",
"ReadCloser",
"{",
"bytesPipe",
":=",
"ioutils",
".",
"NewBytesPipe",
"(",
"nil",
")",
"\n",
"streamConfig",
".",
"stdout",
".",
"Add",
"(",
"bytesPipe",
")",
"\n",
... | // StdoutPipe creates a new io.ReadCloser with an empty bytes pipe.
// It adds this new out pipe to the Stdout broadcaster. | [
"StdoutPipe",
"creates",
"a",
"new",
"io",
".",
"ReadCloser",
"with",
"an",
"empty",
"bytes",
"pipe",
".",
"It",
"adds",
"this",
"new",
"out",
"pipe",
"to",
"the",
"Stdout",
"broadcaster",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/streams.go#L68-L72 | train |
hyperhq/hyperd | daemon/pod/streams.go | StderrPipe | func (streamConfig *StreamConfig) StderrPipe() io.ReadCloser {
bytesPipe := ioutils.NewBytesPipe(nil)
streamConfig.stderr.Add(bytesPipe)
return bytesPipe
} | go | func (streamConfig *StreamConfig) StderrPipe() io.ReadCloser {
bytesPipe := ioutils.NewBytesPipe(nil)
streamConfig.stderr.Add(bytesPipe)
return bytesPipe
} | [
"func",
"(",
"streamConfig",
"*",
"StreamConfig",
")",
"StderrPipe",
"(",
")",
"io",
".",
"ReadCloser",
"{",
"bytesPipe",
":=",
"ioutils",
".",
"NewBytesPipe",
"(",
"nil",
")",
"\n",
"streamConfig",
".",
"stderr",
".",
"Add",
"(",
"bytesPipe",
")",
"\n",
... | // StderrPipe creates a new io.ReadCloser with an empty bytes pipe.
// It adds this new err pipe to the Stderr broadcaster. | [
"StderrPipe",
"creates",
"a",
"new",
"io",
".",
"ReadCloser",
"with",
"an",
"empty",
"bytes",
"pipe",
".",
"It",
"adds",
"this",
"new",
"err",
"pipe",
"to",
"the",
"Stderr",
"broadcaster",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/streams.go#L76-L80 | train |
hyperhq/hyperd | daemon/daemonbuilder/pod.go | ContainerAttach | func (d Docker) ContainerAttach(cId string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool) error {
<-d.hyper.Ready
err := d.Daemon.Attach(stdin, ioutils.NopWriteCloser(stdout), cId)
if err != nil {
return err
}
code, err := d.Daemon.ExitCode(cId, "")
if err != nil {
return err
}
if code == 0 {
return nil
}
return &jsonmessage.JSONError{
Message: fmt.Sprintf("The container '%s' returned a non-zero code: %d", cId, code),
Code: code,
}
} | go | func (d Docker) ContainerAttach(cId string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool) error {
<-d.hyper.Ready
err := d.Daemon.Attach(stdin, ioutils.NopWriteCloser(stdout), cId)
if err != nil {
return err
}
code, err := d.Daemon.ExitCode(cId, "")
if err != nil {
return err
}
if code == 0 {
return nil
}
return &jsonmessage.JSONError{
Message: fmt.Sprintf("The container '%s' returned a non-zero code: %d", cId, code),
Code: code,
}
} | [
"func",
"(",
"d",
"Docker",
")",
"ContainerAttach",
"(",
"cId",
"string",
",",
"stdin",
"io",
".",
"ReadCloser",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
",",
"stream",
"bool",
")",
"error",
"{",
"<-",
"d",
".",
"hyper",
".",
"Ready",
"\n\n... | // ContainerAttach attaches streams to the container cID. If stream is true, it streams the output. | [
"ContainerAttach",
"attaches",
"streams",
"to",
"the",
"container",
"cID",
".",
"If",
"stream",
"is",
"true",
"it",
"streams",
"the",
"output",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/daemonbuilder/pod.go#L26-L47 | train |
hyperhq/hyperd | daemon/daemonbuilder/pod.go | ContainerCreate | func (d Docker) ContainerCreate(params types.ContainerCreateConfig) (types.ContainerCreateResponse, error) {
var spec *apitypes.UserPod
var err error
if params.Config == nil {
return types.ContainerCreateResponse{}, derr.ErrorCodeEmptyConfig
}
podId := fmt.Sprintf("buildpod-%s", utils.RandStr(10, "alpha"))
// Hack here, container created by ADD/COPY only has Config
if params.HostConfig != nil {
spec, err = MakeBasicPod(podId, params.Config, params.HostConfig)
} else {
spec, err = MakeCopyPod(podId, params.Config)
}
if err != nil {
return types.ContainerCreateResponse{}, err
}
p, err := d.Daemon.CreatePod(podId, spec)
if err != nil {
return types.ContainerCreateResponse{}, err
}
containers := p.ContainerIds()
if len(containers) != 1 {
return types.ContainerCreateResponse{}, fmt.Errorf("container count in pod is incorrect")
}
cId := containers[0]
if params.HostConfig != nil {
d.hyper.BasicPods[cId] = podId
glog.Infof("basic containerId %s, podId %s", cId, podId)
} else {
d.hyper.CopyPods[cId] = podId
glog.Infof("copy containerId %s, podId %s", cId, podId)
}
return types.ContainerCreateResponse{ID: cId}, nil
} | go | func (d Docker) ContainerCreate(params types.ContainerCreateConfig) (types.ContainerCreateResponse, error) {
var spec *apitypes.UserPod
var err error
if params.Config == nil {
return types.ContainerCreateResponse{}, derr.ErrorCodeEmptyConfig
}
podId := fmt.Sprintf("buildpod-%s", utils.RandStr(10, "alpha"))
// Hack here, container created by ADD/COPY only has Config
if params.HostConfig != nil {
spec, err = MakeBasicPod(podId, params.Config, params.HostConfig)
} else {
spec, err = MakeCopyPod(podId, params.Config)
}
if err != nil {
return types.ContainerCreateResponse{}, err
}
p, err := d.Daemon.CreatePod(podId, spec)
if err != nil {
return types.ContainerCreateResponse{}, err
}
containers := p.ContainerIds()
if len(containers) != 1 {
return types.ContainerCreateResponse{}, fmt.Errorf("container count in pod is incorrect")
}
cId := containers[0]
if params.HostConfig != nil {
d.hyper.BasicPods[cId] = podId
glog.Infof("basic containerId %s, podId %s", cId, podId)
} else {
d.hyper.CopyPods[cId] = podId
glog.Infof("copy containerId %s, podId %s", cId, podId)
}
return types.ContainerCreateResponse{ID: cId}, nil
} | [
"func",
"(",
"d",
"Docker",
")",
"ContainerCreate",
"(",
"params",
"types",
".",
"ContainerCreateConfig",
")",
"(",
"types",
".",
"ContainerCreateResponse",
",",
"error",
")",
"{",
"var",
"spec",
"*",
"apitypes",
".",
"UserPod",
"\n",
"var",
"err",
"error",
... | // Override the Docker ContainerCreate interface, create pod to run command | [
"Override",
"the",
"Docker",
"ContainerCreate",
"interface",
"create",
"pod",
"to",
"run",
"command"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/daemonbuilder/pod.go#L210-L250 | train |
hyperhq/hyperd | server/server_windows.go | newServer | func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
var (
ls []net.Listener
)
switch proto {
case "tcp":
l, err := s.initTCPSocket(addr)
if err != nil {
return nil, err
}
ls = append(ls, l)
default:
return nil, errors.New("Invalid protocol format. Windows only supports tcp.")
}
var res []*HTTPServer
for _, l := range ls {
res = append(res, &HTTPServer{
&http.Server{
Addr: addr,
},
l,
})
}
return res, nil
} | go | func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
var (
ls []net.Listener
)
switch proto {
case "tcp":
l, err := s.initTCPSocket(addr)
if err != nil {
return nil, err
}
ls = append(ls, l)
default:
return nil, errors.New("Invalid protocol format. Windows only supports tcp.")
}
var res []*HTTPServer
for _, l := range ls {
res = append(res, &HTTPServer{
&http.Server{
Addr: addr,
},
l,
})
}
return res, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"newServer",
"(",
"proto",
",",
"addr",
"string",
")",
"(",
"[",
"]",
"*",
"HTTPServer",
",",
"error",
")",
"{",
"var",
"(",
"ls",
"[",
"]",
"net",
".",
"Listener",
"\n",
")",
"\n",
"switch",
"proto",
"{",
... | // NewServer sets up the required Server and does protocol specific checking. | [
"NewServer",
"sets",
"up",
"the",
"required",
"Server",
"and",
"does",
"protocol",
"specific",
"checking",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/server_windows.go#L12-L39 | train |
hyperhq/hyperd | server/router/local/local.go | NewRoute | func NewRoute(method, path string, handler httputils.APIFunc) dkrouter.Route {
return localRoute{method, path, handler}
} | go | func NewRoute(method, path string, handler httputils.APIFunc) dkrouter.Route {
return localRoute{method, path, handler}
} | [
"func",
"NewRoute",
"(",
"method",
",",
"path",
"string",
",",
"handler",
"httputils",
".",
"APIFunc",
")",
"dkrouter",
".",
"Route",
"{",
"return",
"localRoute",
"{",
"method",
",",
"path",
",",
"handler",
"}",
"\n",
"}"
] | // NewRoute initializes a new local router for the reouter | [
"NewRoute",
"initializes",
"a",
"new",
"local",
"router",
"for",
"the",
"reouter"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/router/local/local.go#L39-L41 | train |
hyperhq/hyperd | server/router/local/local.go | NewRouter | func NewRouter(daemon *daemon.Daemon) dkrouter.Router {
r := &router{
daemon: daemon,
}
r.initRoutes()
return r
} | go | func NewRouter(daemon *daemon.Daemon) dkrouter.Router {
r := &router{
daemon: daemon,
}
r.initRoutes()
return r
} | [
"func",
"NewRouter",
"(",
"daemon",
"*",
"daemon",
".",
"Daemon",
")",
"dkrouter",
".",
"Router",
"{",
"r",
":=",
"&",
"router",
"{",
"daemon",
":",
"daemon",
",",
"}",
"\n",
"r",
".",
"initRoutes",
"(",
")",
"\n",
"return",
"r",
"\n",
"}"
] | // NewRouter initializes a local router with a new daemon. | [
"NewRouter",
"initializes",
"a",
"local",
"router",
"with",
"a",
"new",
"daemon",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/router/local/local.go#L74-L80 | train |
hyperhq/hyperd | server/router/local/local.go | initRoutes | func (r *router) initRoutes() {
r.routes = []dkrouter.Route{
// OPTIONS
// GET
// /images/json in docker
NewGetRoute("/images/get", r.getImagesJSON),
// /images/get in docker
NewGetRoute("/images/save", r.getImagesSave),
// POST
NewPostRoute("/image/create", r.postImagesCreate),
NewPostRoute("/image/load", r.postImagesLoad),
NewPostRoute("/image/push", r.postImagesPush),
// DELETE
NewDeleteRoute("/image", r.deleteImages),
}
} | go | func (r *router) initRoutes() {
r.routes = []dkrouter.Route{
// OPTIONS
// GET
// /images/json in docker
NewGetRoute("/images/get", r.getImagesJSON),
// /images/get in docker
NewGetRoute("/images/save", r.getImagesSave),
// POST
NewPostRoute("/image/create", r.postImagesCreate),
NewPostRoute("/image/load", r.postImagesLoad),
NewPostRoute("/image/push", r.postImagesPush),
// DELETE
NewDeleteRoute("/image", r.deleteImages),
}
} | [
"func",
"(",
"r",
"*",
"router",
")",
"initRoutes",
"(",
")",
"{",
"r",
".",
"routes",
"=",
"[",
"]",
"dkrouter",
".",
"Route",
"{",
"// OPTIONS",
"// GET",
"// /images/json in docker",
"NewGetRoute",
"(",
"\"",
"\"",
",",
"r",
".",
"getImagesJSON",
")",... | // initRoutes initializes the routes in this router | [
"initRoutes",
"initializes",
"the",
"routes",
"in",
"this",
"router"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/router/local/local.go#L88-L103 | train |
hyperhq/hyperd | daemon/pod/container.go | initStreams | func (c *Container) initStreams() error {
if c.streams != nil {
return nil
}
if !c.p.IsAlive() {
c.Log(ERROR, "can not init stream to a non-existing sandbox")
return errors.ErrPodNotAlive.WithArgs(c.p.Id())
}
c.Log(TRACE, "init io streams")
c.streams = NewStreamConfig()
c.streams.NewInputPipes()
tty := &hypervisor.TtyIO{
Stdin: c.streams.Stdin(),
Stdout: c.streams.Stdout(),
Stderr: c.streams.Stderr(),
}
if err := c.p.sandbox.Attach(tty, c.Id()); err != nil {
c.Log(ERROR, err)
return err
}
return nil
} | go | func (c *Container) initStreams() error {
if c.streams != nil {
return nil
}
if !c.p.IsAlive() {
c.Log(ERROR, "can not init stream to a non-existing sandbox")
return errors.ErrPodNotAlive.WithArgs(c.p.Id())
}
c.Log(TRACE, "init io streams")
c.streams = NewStreamConfig()
c.streams.NewInputPipes()
tty := &hypervisor.TtyIO{
Stdin: c.streams.Stdin(),
Stdout: c.streams.Stdout(),
Stderr: c.streams.Stderr(),
}
if err := c.p.sandbox.Attach(tty, c.Id()); err != nil {
c.Log(ERROR, err)
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"Container",
")",
"initStreams",
"(",
")",
"error",
"{",
"if",
"c",
".",
"streams",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"p",
".",
"IsAlive",
"(",
")",
"{",
"c",
".",
"Log",
"(",
"ERR... | // This method should be called when initialzing container or put into resource lock. | [
"This",
"method",
"should",
"be",
"called",
"when",
"initialzing",
"container",
"or",
"put",
"into",
"resource",
"lock",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/container.go#L945-L966 | train |
hyperhq/hyperd | daemon/pod/container.go | Create | func (cs *ContainerStatus) Create() error {
cs.Lock()
defer cs.Unlock()
if cs.State != S_CONTAINER_NONE {
err := fmt.Errorf("only NONE container could be create, current: %d", cs.State)
return err
}
cs.State = S_CONTAINER_CREATING
cs.stateChanged.Broadcast()
return nil
} | go | func (cs *ContainerStatus) Create() error {
cs.Lock()
defer cs.Unlock()
if cs.State != S_CONTAINER_NONE {
err := fmt.Errorf("only NONE container could be create, current: %d", cs.State)
return err
}
cs.State = S_CONTAINER_CREATING
cs.stateChanged.Broadcast()
return nil
} | [
"func",
"(",
"cs",
"*",
"ContainerStatus",
")",
"Create",
"(",
")",
"error",
"{",
"cs",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cs",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"cs",
".",
"State",
"!=",
"S_CONTAINER_NONE",
"{",
"err",
":=",
"fmt",
".",
... | // container status transition | [
"container",
"status",
"transition"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/daemon/pod/container.go#L1196-L1209 | train |
hyperhq/hyperd | storage/devicemapper/dm.go | DMCleanup | func DMCleanup(dm *DeviceMapper) error {
var parms string
// Delete the thin pool for test
parms = fmt.Sprintf("dmsetup remove \"/dev/mapper/%s\"", dm.PoolName)
if res, err := exec.Command("/bin/sh", "-c", parms).CombinedOutput(); err != nil {
glog.Error(string(res))
return fmt.Errorf(string(res))
}
// Delete the loop device
parms = fmt.Sprintf("losetup -d %s", dm.MetadataLoopFile)
if res, err := exec.Command("/bin/sh", "-c", parms).CombinedOutput(); err != nil {
glog.Error(string(res))
return fmt.Errorf(string(res))
}
parms = fmt.Sprintf("losetup -d %s", dm.DataLoopFile)
if res, err := exec.Command("/bin/sh", "-c", parms).CombinedOutput(); err != nil {
glog.Error(string(res))
return fmt.Errorf(string(res))
}
return nil
} | go | func DMCleanup(dm *DeviceMapper) error {
var parms string
// Delete the thin pool for test
parms = fmt.Sprintf("dmsetup remove \"/dev/mapper/%s\"", dm.PoolName)
if res, err := exec.Command("/bin/sh", "-c", parms).CombinedOutput(); err != nil {
glog.Error(string(res))
return fmt.Errorf(string(res))
}
// Delete the loop device
parms = fmt.Sprintf("losetup -d %s", dm.MetadataLoopFile)
if res, err := exec.Command("/bin/sh", "-c", parms).CombinedOutput(); err != nil {
glog.Error(string(res))
return fmt.Errorf(string(res))
}
parms = fmt.Sprintf("losetup -d %s", dm.DataLoopFile)
if res, err := exec.Command("/bin/sh", "-c", parms).CombinedOutput(); err != nil {
glog.Error(string(res))
return fmt.Errorf(string(res))
}
return nil
} | [
"func",
"DMCleanup",
"(",
"dm",
"*",
"DeviceMapper",
")",
"error",
"{",
"var",
"parms",
"string",
"\n",
"// Delete the thin pool for test",
"parms",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"dm",
".",
"PoolName",
")",
"\n",
"if",
... | // Delete the pool which is created in 'Init' function | [
"Delete",
"the",
"pool",
"which",
"is",
"created",
"in",
"Init",
"function"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/storage/devicemapper/dm.go#L295-L315 | train |
hyperhq/hyperd | server/httputils/httputils.go | ParseMultipartForm | func ParseMultipartForm(r *http.Request) error {
if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
return err
}
return nil
} | go | func ParseMultipartForm(r *http.Request) error {
if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
return err
}
return nil
} | [
"func",
"ParseMultipartForm",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"err",
":=",
"r",
".",
"ParseMultipartForm",
"(",
"4096",
")",
";",
"err",
"!=",
"nil",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"err",
".",
"Error",
"(... | // ParseMultipartForm ensure the request form is parsed, even with invalid content types. | [
"ParseMultipartForm",
"ensure",
"the",
"request",
"form",
"is",
"parsed",
"even",
"with",
"invalid",
"content",
"types",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/httputils/httputils.go#L81-L86 | train |
hyperhq/hyperd | server/httputils/httputils.go | WriteError | func WriteError(w http.ResponseWriter, err error) {
if err == nil || w == nil {
glog.Errorf("unexpected HTTP error handling, error %v, writer %v", err, w)
return
}
statusCode := http.StatusInternalServerError
errMsg := err.Error()
// Based on the type of error we get we need to process things
// slightly differently to extract the error message.
// In the 'errcode.*' cases there are two different type of
// error that could be returned. errocode.ErrorCode is the base
// type of error object - it is just an 'int' that can then be
// used as the look-up key to find the message. errorcode.Error
// extends errorcode.Error by adding error-instance specific
// data, like 'details' or variable strings to be inserted into
// the message.
//
// Ideally, we should just be able to call err.Error() for all
// cases but the errcode package doesn't support that yet.
//
// Additionally, in both errcode cases, there might be an http
// status code associated with it, and if so use it.
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
if statusCode == 0 {
statusCode = http.StatusInternalServerError
}
http.Error(w, errMsg, statusCode)
} | go | func WriteError(w http.ResponseWriter, err error) {
if err == nil || w == nil {
glog.Errorf("unexpected HTTP error handling, error %v, writer %v", err, w)
return
}
statusCode := http.StatusInternalServerError
errMsg := err.Error()
// Based on the type of error we get we need to process things
// slightly differently to extract the error message.
// In the 'errcode.*' cases there are two different type of
// error that could be returned. errocode.ErrorCode is the base
// type of error object - it is just an 'int' that can then be
// used as the look-up key to find the message. errorcode.Error
// extends errorcode.Error by adding error-instance specific
// data, like 'details' or variable strings to be inserted into
// the message.
//
// Ideally, we should just be able to call err.Error() for all
// cases but the errcode package doesn't support that yet.
//
// Additionally, in both errcode cases, there might be an http
// status code associated with it, and if so use it.
switch err.(type) {
case errcode.ErrorCode:
daError, _ := err.(errcode.ErrorCode)
statusCode = daError.Descriptor().HTTPStatusCode
errMsg = daError.Message()
case errcode.Error:
// For reference, if you're looking for a particular error
// then you can do something like :
// import ( derr "github.com/docker/docker/errors" )
// if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
daError, _ := err.(errcode.Error)
statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
errMsg = daError.Message
default:
// This part of will be removed once we've
// converted everything over to use the errcode package
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types,
// we should create appropriate error types with clearly defined meaning
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
}
if statusCode == 0 {
statusCode = http.StatusInternalServerError
}
http.Error(w, errMsg, statusCode)
} | [
"func",
"WriteError",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"err",
"error",
")",
"{",
"if",
"err",
"==",
"nil",
"||",
"w",
"==",
"nil",
"{",
"glog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"w",
")",
"\n",
"return",
"\n",
"}",
"... | // WriteError decodes a specific docker error and sends it in the response. | [
"WriteError",
"decodes",
"a",
"specific",
"docker",
"error",
"and",
"sends",
"it",
"in",
"the",
"response",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/server/httputils/httputils.go#L89-L158 | train |
hyperhq/hyperd | image/tarexport/tarexport.go | NewTarExporter | func NewTarExporter(is image.Store, ls layer.Store, rs reference.Store) hyperimage.Exporter {
return &tarexporter{
is: is,
ls: ls,
rs: rs,
}
} | go | func NewTarExporter(is image.Store, ls layer.Store, rs reference.Store) hyperimage.Exporter {
return &tarexporter{
is: is,
ls: ls,
rs: rs,
}
} | [
"func",
"NewTarExporter",
"(",
"is",
"image",
".",
"Store",
",",
"ls",
"layer",
".",
"Store",
",",
"rs",
"reference",
".",
"Store",
")",
"hyperimage",
".",
"Exporter",
"{",
"return",
"&",
"tarexporter",
"{",
"is",
":",
"is",
",",
"ls",
":",
"ls",
","... | // NewTarExporter returns new ImageExporter for tar packages | [
"NewTarExporter",
"returns",
"new",
"ImageExporter",
"for",
"tar",
"packages"
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/image/tarexport/tarexport.go#L31-L37 | train |
hyperhq/hyperd | storage/graphdriver/rawblock/driver.go | Init | func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
backingFs := "<unknown>"
blockFs := "xfs" // TODO: make it configurable
cow := true
supported := "supported"
fsMagic, err := graphdriver.GetFSMagic(home)
if err != nil {
return nil, err
}
if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
backingFs = fsName
}
// check if they are running over btrfs or xfs
switch fsMagic {
case graphdriver.FsMagicBtrfs: // support
case graphdriver.FsMagicXfs: // check support
if testReflinkSupport(home) {
break
}
fallthrough
default:
cow = false
supported = "NOT supported"
}
glog.Infof("RawBlock: copy-on-write is %s", supported)
rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
if err != nil {
return nil, err
}
if err := idtools.MkdirAllAs(home, 0700, rootUID, rootGID); err != nil {
return nil, err
}
var blockSize = uint64(10 * 1024 * 1024 * 1024)
for _, option := range options {
key, val, err := parsers.ParseKeyValueOpt(option)
if err != nil {
return nil, err
}
key = strings.ToLower(key)
switch key {
case "rawblock.basesize":
size, err := units.RAMInBytes(val)
if err != nil {
return nil, err
}
blockSize = uint64(size)
default:
return nil, fmt.Errorf("rawblock: Unknown option %s\n", key)
}
}
d := &Driver{
home: home,
backingFs: backingFs,
cow: cow,
blockFs: blockFs,
blockSize: blockSize,
uid: rootUID,
gid: rootGID,
active: map[string]int{},
}
return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil
} | go | func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
backingFs := "<unknown>"
blockFs := "xfs" // TODO: make it configurable
cow := true
supported := "supported"
fsMagic, err := graphdriver.GetFSMagic(home)
if err != nil {
return nil, err
}
if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
backingFs = fsName
}
// check if they are running over btrfs or xfs
switch fsMagic {
case graphdriver.FsMagicBtrfs: // support
case graphdriver.FsMagicXfs: // check support
if testReflinkSupport(home) {
break
}
fallthrough
default:
cow = false
supported = "NOT supported"
}
glog.Infof("RawBlock: copy-on-write is %s", supported)
rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
if err != nil {
return nil, err
}
if err := idtools.MkdirAllAs(home, 0700, rootUID, rootGID); err != nil {
return nil, err
}
var blockSize = uint64(10 * 1024 * 1024 * 1024)
for _, option := range options {
key, val, err := parsers.ParseKeyValueOpt(option)
if err != nil {
return nil, err
}
key = strings.ToLower(key)
switch key {
case "rawblock.basesize":
size, err := units.RAMInBytes(val)
if err != nil {
return nil, err
}
blockSize = uint64(size)
default:
return nil, fmt.Errorf("rawblock: Unknown option %s\n", key)
}
}
d := &Driver{
home: home,
backingFs: backingFs,
cow: cow,
blockFs: blockFs,
blockSize: blockSize,
uid: rootUID,
gid: rootGID,
active: map[string]int{},
}
return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil
} | [
"func",
"Init",
"(",
"home",
"string",
",",
"options",
"[",
"]",
"string",
",",
"uidMaps",
",",
"gidMaps",
"[",
"]",
"idtools",
".",
"IDMap",
")",
"(",
"graphdriver",
".",
"Driver",
",",
"error",
")",
"{",
"backingFs",
":=",
"\"",
"\"",
"\n",
"blockF... | // Init returns a new Raw Block driver.
// This sets the home directory for the driver and returns NaiveDiffDriver. | [
"Init",
"returns",
"a",
"new",
"Raw",
"Block",
"driver",
".",
"This",
"sets",
"the",
"home",
"directory",
"for",
"the",
"driver",
"and",
"returns",
"NaiveDiffDriver",
"."
] | 8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956 | https://github.com/hyperhq/hyperd/blob/8a7e67dc33bbccdfc92b5e2a908bbdb1c5d9b956/storage/graphdriver/rawblock/driver.go#L58-L124 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.