repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
qor/qor-example
app/products/handlers.go
Index
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { var ( Products []products.Product tx = utils.GetDB(req) ) tx.Preload("Category").Find(&Products) ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
go
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { var ( Products []products.Product tx = utils.GetDB(req) ) tx.Preload("Category").Find(&Products) ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Index", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "Products", "[", "]", "products", ".", "Product", "\n", "tx", "=", "utils", ".", "GetDB", "(", ...
// Index products index page
[ "Index", "products", "index", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/products/handlers.go#L18-L27
train
qor/qor-example
app/products/handlers.go
Show
func (ctrl Controller) Show(w http.ResponseWriter, req *http.Request) { var ( product products.Product colorVariation products.ColorVariation codes = strings.Split(utils.URLParam("code", req), "_") productCode = codes[0] colorCode string tx = utils.GetDB(req) ) if len(codes) > 1 { colorCode = codes[1] } if tx.Preload("Category").Where(&products.Product{Code: productCode}).First(&product).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Preload("Product").Preload("Color").Preload("SizeVariations.Size").Where(&products.ColorVariation{ProductID: product.ID, ColorCode: colorCode}).First(&colorVariation) ctrl.View.Execute("show", map[string]interface{}{"CurrentColorVariation": colorVariation}, req, w) }
go
func (ctrl Controller) Show(w http.ResponseWriter, req *http.Request) { var ( product products.Product colorVariation products.ColorVariation codes = strings.Split(utils.URLParam("code", req), "_") productCode = codes[0] colorCode string tx = utils.GetDB(req) ) if len(codes) > 1 { colorCode = codes[1] } if tx.Preload("Category").Where(&products.Product{Code: productCode}).First(&product).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Preload("Product").Preload("Color").Preload("SizeVariations.Size").Where(&products.ColorVariation{ProductID: product.ID, ColorCode: colorCode}).First(&colorVariation) ctrl.View.Execute("show", map[string]interface{}{"CurrentColorVariation": colorVariation}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Show", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "product", "products", ".", "Product", "\n", "colorVariation", "products", ".", "ColorVariation", "\n", ...
// Show product show page
[ "Show", "product", "show", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/products/handlers.go#L42-L63
train
qor/qor-example
app/products/handlers.go
Category
func (ctrl Controller) Category(w http.ResponseWriter, req *http.Request) { var ( category products.Category Products []products.Product tx = utils.GetDB(req) ) if tx.Where("code = ?", utils.URLParam("code", req)).First(&category).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Where(&products.Product{CategoryID: category.ID}).Preload("ColorVariations").Find(&Products) ctrl.View.Execute("category", map[string]interface{}{"CategoryName": category.Name, "Products": Products}, req, w) }
go
func (ctrl Controller) Category(w http.ResponseWriter, req *http.Request) { var ( category products.Category Products []products.Product tx = utils.GetDB(req) ) if tx.Where("code = ?", utils.URLParam("code", req)).First(&category).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Where(&products.Product{CategoryID: category.ID}).Preload("ColorVariations").Find(&Products) ctrl.View.Execute("category", map[string]interface{}{"CategoryName": category.Name, "Products": Products}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Category", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "category", "products", ".", "Category", "\n", "Products", "[", "]", "products", ".", "Product", ...
// Category category show page
[ "Category", "category", "show", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/products/handlers.go#L66-L80
train
qor/qor-example
app/orders/handlers.go
Cart
func (ctrl Controller) Cart(w http.ResponseWriter, req *http.Request) { order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("cart", map[string]interface{}{"Order": order}, req, w) }
go
func (ctrl Controller) Cart(w http.ResponseWriter, req *http.Request) { order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("cart", map[string]interface{}{"Order": order}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Cart", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "order", ":=", "getCurrentOrderWithItems", "(", "w", ",", "req", ")", "\n", "ctrl", ".", "View", ".", "Execute",...
// Cart shopping cart
[ "Cart", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L27-L30
train
qor/qor-example
app/orders/handlers.go
Checkout
func (ctrl Controller) Checkout(w http.ResponseWriter, req *http.Request) { hasAmazon := req.URL.Query().Get("access_token") order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("checkout", map[string]interface{}{"Order": order, "HasAmazon": hasAmazon}, req, w) }
go
func (ctrl Controller) Checkout(w http.ResponseWriter, req *http.Request) { hasAmazon := req.URL.Query().Get("access_token") order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("checkout", map[string]interface{}{"Order": order, "HasAmazon": hasAmazon}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Checkout", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "hasAmazon", ":=", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"access_token\"", ")", "\...
// Checkout checkout shopping cart
[ "Checkout", "checkout", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L33-L37
train
qor/qor-example
app/orders/handlers.go
Complete
func (ctrl Controller) Complete(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) if order.AmazonOrderReferenceID = req.Form.Get("amazon_order_reference_id"); order.AmazonOrderReferenceID != "" { order.AmazonAddressAccessToken = req.Form.Get("amazon_address_access_token") tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } utils.AddFlashMessage(w, req, err.Error(), "error") } else { utils.AddFlashMessage(w, req, "Order Reference ID not Found", "error") } http.Redirect(w, req, "/cart", http.StatusFound) }
go
func (ctrl Controller) Complete(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) if order.AmazonOrderReferenceID = req.Form.Get("amazon_order_reference_id"); order.AmazonOrderReferenceID != "" { order.AmazonAddressAccessToken = req.Form.Get("amazon_address_access_token") tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } utils.AddFlashMessage(w, req, err.Error(), "error") } else { utils.AddFlashMessage(w, req, "Order Reference ID not Found", "error") } http.Redirect(w, req, "/cart", http.StatusFound) }
[ "func", "(", "ctrl", "Controller", ")", "Complete", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "req", ".", "ParseForm", "(", ")", "\n", "order", ":=", "getCurrentOrder", "(", "w", ",", "req", ")", "\n"...
// Complete complete shopping cart
[ "Complete", "complete", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L40-L60
train
qor/qor-example
app/orders/handlers.go
CompleteCreditCard
func (ctrl Controller) CompleteCreditCard(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) expMonth, _ := strconv.Atoi(req.Form.Get("exp_month")) expYear, _ := strconv.Atoi(req.Form.Get("exp_year")) creditCard := gomerchant.CreditCard{ Name: req.Form.Get("name"), Number: req.Form.Get("creditcard"), CVC: req.Form.Get("cvv"), ExpYear: uint(expYear), ExpMonth: uint(expMonth), } if creditCard.ValidNumber() { // TODO integrate with https://github.com/qor/gomerchant to handle those information tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } } utils.AddFlashMessage(w, req, "Invalid Credit Card", "error") http.Redirect(w, req, "/cart", http.StatusFound) }
go
func (ctrl Controller) CompleteCreditCard(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) expMonth, _ := strconv.Atoi(req.Form.Get("exp_month")) expYear, _ := strconv.Atoi(req.Form.Get("exp_year")) creditCard := gomerchant.CreditCard{ Name: req.Form.Get("name"), Number: req.Form.Get("creditcard"), CVC: req.Form.Get("cvv"), ExpYear: uint(expYear), ExpMonth: uint(expMonth), } if creditCard.ValidNumber() { // TODO integrate with https://github.com/qor/gomerchant to handle those information tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } } utils.AddFlashMessage(w, req, "Invalid Credit Card", "error") http.Redirect(w, req, "/cart", http.StatusFound) }
[ "func", "(", "ctrl", "Controller", ")", "CompleteCreditCard", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "req", ".", "ParseForm", "(", ")", "\n", "order", ":=", "getCurrentOrder", "(", "w", ",", "req", "...
// CompleteCreditCard complete shopping cart with credit card
[ "CompleteCreditCard", "complete", "shopping", "cart", "with", "credit", "card" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L63-L93
train
qor/qor-example
app/orders/handlers.go
UpdateCart
func (ctrl Controller) UpdateCart(w http.ResponseWriter, req *http.Request) { var ( input updateCartInput tx = utils.GetDB(req) ) req.ParseForm() decoder.Decode(&input, req.PostForm) order := getCurrentOrder(w, req) if input.Quantity > 0 { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Assign(&orders.OrderItem{Quantity: input.Quantity}). FirstOrCreate(&orders.OrderItem{}) } else { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Delete(&orders.OrderItem{}) } responder.With("html", func() { http.Redirect(w, req, "/cart", http.StatusFound) }).With([]string{"json", "xml"}, func() { config.Render.JSON(w, http.StatusOK, map[string]string{"status": "ok"}) }).Respond(req) }
go
func (ctrl Controller) UpdateCart(w http.ResponseWriter, req *http.Request) { var ( input updateCartInput tx = utils.GetDB(req) ) req.ParseForm() decoder.Decode(&input, req.PostForm) order := getCurrentOrder(w, req) if input.Quantity > 0 { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Assign(&orders.OrderItem{Quantity: input.Quantity}). FirstOrCreate(&orders.OrderItem{}) } else { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Delete(&orders.OrderItem{}) } responder.With("html", func() { http.Redirect(w, req, "/cart", http.StatusFound) }).With([]string{"json", "xml"}, func() { config.Render.JSON(w, http.StatusOK, map[string]string{"status": "ok"}) }).Respond(req) }
[ "func", "(", "ctrl", "Controller", ")", "UpdateCart", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "input", "updateCartInput", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", "...
// UpdateCart update shopping cart
[ "UpdateCart", "update", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L108-L133
train
qor/qor-example
app/orders/handlers.go
AmazonCallback
func (ctrl Controller) AmazonCallback(w http.ResponseWriter, req *http.Request) { ipn, ok := amazonpay.VerifyIPNRequest(req) fmt.Printf("%#v\n", ipn) fmt.Printf("%#v\n", ok) }
go
func (ctrl Controller) AmazonCallback(w http.ResponseWriter, req *http.Request) { ipn, ok := amazonpay.VerifyIPNRequest(req) fmt.Printf("%#v\n", ipn) fmt.Printf("%#v\n", ok) }
[ "func", "(", "ctrl", "Controller", ")", "AmazonCallback", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ipn", ",", "ok", ":=", "amazonpay", ".", "VerifyIPNRequest", "(", "req", ")", "\n", "fmt", ".", "Prin...
// AmazonCallback amazon callback
[ "AmazonCallback", "amazon", "callback" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L136-L140
train
qor/qor-example
models/products/product.go
ViewPath
func (colorVariation ColorVariation) ViewPath() string { defaultPath := "" var product Product if !db.DB.First(&product, "id = ?", colorVariation.ProductID).RecordNotFound() { defaultPath = fmt.Sprintf("/products/%s_%s", product.Code, colorVariation.ColorCode) } return defaultPath }
go
func (colorVariation ColorVariation) ViewPath() string { defaultPath := "" var product Product if !db.DB.First(&product, "id = ?", colorVariation.ProductID).RecordNotFound() { defaultPath = fmt.Sprintf("/products/%s_%s", product.Code, colorVariation.ColorCode) } return defaultPath }
[ "func", "(", "colorVariation", "ColorVariation", ")", "ViewPath", "(", ")", "string", "{", "defaultPath", ":=", "\"\"", "\n", "var", "product", "Product", "\n", "if", "!", "db", ".", "DB", ".", "First", "(", "&", "product", ",", "\"id = ?\"", ",", "color...
// ViewPath view path of color variation
[ "ViewPath", "view", "path", "of", "color", "variation" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/products/product.go#L200-L207
train
qor/qor-example
utils/funcmapmaker/funcmapmaker.go
GetEditMode
func GetEditMode(w http.ResponseWriter, req *http.Request) bool { return admin.ActionBar.EditMode(w, req) }
go
func GetEditMode(w http.ResponseWriter, req *http.Request) bool { return admin.ActionBar.EditMode(w, req) }
[ "func", "GetEditMode", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "bool", "{", "return", "admin", ".", "ActionBar", ".", "EditMode", "(", "w", ",", "req", ")", "\n", "}" ]
// GetEditMode get edit mode
[ "GetEditMode", "get", "edit", "mode" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/funcmapmaker/funcmapmaker.go#L24-L26
train
qor/qor-example
app/account/handlers.go
Profile
func (ctrl Controller) Profile(w http.ResponseWriter, req *http.Request) { var ( currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) billingAddress, shippingAddress users.Address ) // TODO refactor tx.Model(currentUser).Related(&currentUser.Addresses, "Addresses") tx.Model(currentUser).Related(&billingAddress, "DefaultBillingAddress") tx.Model(currentUser).Related(&shippingAddress, "DefaultShippingAddress") ctrl.View.Execute("profile", map[string]interface{}{ "CurrentUser": currentUser, "DefaultBillingAddress": billingAddress, "DefaultShippingAddress": shippingAddress, }, req, w) }
go
func (ctrl Controller) Profile(w http.ResponseWriter, req *http.Request) { var ( currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) billingAddress, shippingAddress users.Address ) // TODO refactor tx.Model(currentUser).Related(&currentUser.Addresses, "Addresses") tx.Model(currentUser).Related(&billingAddress, "DefaultBillingAddress") tx.Model(currentUser).Related(&shippingAddress, "DefaultShippingAddress") ctrl.View.Execute("profile", map[string]interface{}{ "CurrentUser": currentUser, "DefaultBillingAddress": billingAddress, "DefaultShippingAddress": shippingAddress, }, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Profile", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "currentUser", "=", "utils", ".", "GetCurrentUser", "(", "req", ")", "\n", "tx", "=", "utils", ...
// Profile profile show page
[ "Profile", "profile", "show", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/account/handlers.go#L18-L33
train
qor/qor-example
app/account/handlers.go
Orders
func (ctrl Controller) Orders(w http.ResponseWriter, req *http.Request) { var ( Orders []orders.Order currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) ) tx.Preload("OrderItems").Where("state <> ? AND state != ?", orders.DraftState, "").Where(&orders.Order{UserID: &currentUser.ID}).Find(&Orders) ctrl.View.Execute("orders", map[string]interface{}{"Orders": Orders}, req, w) }
go
func (ctrl Controller) Orders(w http.ResponseWriter, req *http.Request) { var ( Orders []orders.Order currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) ) tx.Preload("OrderItems").Where("state <> ? AND state != ?", orders.DraftState, "").Where(&orders.Order{UserID: &currentUser.ID}).Find(&Orders) ctrl.View.Execute("orders", map[string]interface{}{"Orders": Orders}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Orders", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "Orders", "[", "]", "orders", ".", "Order", "\n", "currentUser", "=", "utils", ".", "GetCurrentUse...
// Orders orders page
[ "Orders", "orders", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/account/handlers.go#L36-L46
train
qor/qor-example
utils/utils.go
GetCurrentUser
func GetCurrentUser(req *http.Request) *users.User { if currentUser, ok := auth.Auth.GetCurrentUser(req).(*users.User); ok { return currentUser } return nil }
go
func GetCurrentUser(req *http.Request) *users.User { if currentUser, ok := auth.Auth.GetCurrentUser(req).(*users.User); ok { return currentUser } return nil }
[ "func", "GetCurrentUser", "(", "req", "*", "http", ".", "Request", ")", "*", "users", ".", "User", "{", "if", "currentUser", ",", "ok", ":=", "auth", ".", "Auth", ".", "GetCurrentUser", "(", "req", ")", ".", "(", "*", "users", ".", "User", ")", ";"...
// GetCurrentUser get current user from request
[ "GetCurrentUser", "get", "current", "user", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L21-L26
train
qor/qor-example
utils/utils.go
GetCurrentLocale
func GetCurrentLocale(req *http.Request) string { locale := l10n.Global if cookie, err := req.Cookie("locale"); err == nil { locale = cookie.Value } return locale }
go
func GetCurrentLocale(req *http.Request) string { locale := l10n.Global if cookie, err := req.Cookie("locale"); err == nil { locale = cookie.Value } return locale }
[ "func", "GetCurrentLocale", "(", "req", "*", "http", ".", "Request", ")", "string", "{", "locale", ":=", "l10n", ".", "Global", "\n", "if", "cookie", ",", "err", ":=", "req", ".", "Cookie", "(", "\"locale\"", ")", ";", "err", "==", "nil", "{", "local...
// GetCurrentLocale get current locale from request
[ "GetCurrentLocale", "get", "current", "locale", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L29-L35
train
qor/qor-example
utils/utils.go
GetDB
func GetDB(req *http.Request) *gorm.DB { if db := utils.GetDBFromRequest(req); db != nil { return db } return db.DB }
go
func GetDB(req *http.Request) *gorm.DB { if db := utils.GetDBFromRequest(req); db != nil { return db } return db.DB }
[ "func", "GetDB", "(", "req", "*", "http", ".", "Request", ")", "*", "gorm", ".", "DB", "{", "if", "db", ":=", "utils", ".", "GetDBFromRequest", "(", "req", ")", ";", "db", "!=", "nil", "{", "return", "db", "\n", "}", "\n", "return", "db", ".", ...
// GetDB get DB from request
[ "GetDB", "get", "DB", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L38-L43
train
qor/qor-example
utils/utils.go
URLParam
func URLParam(name string, req *http.Request) string { return chi.URLParam(req, name) }
go
func URLParam(name string, req *http.Request) string { return chi.URLParam(req, name) }
[ "func", "URLParam", "(", "name", "string", ",", "req", "*", "http", ".", "Request", ")", "string", "{", "return", "chi", ".", "URLParam", "(", "req", ",", "name", ")", "\n", "}" ]
// URLParam get url params from request
[ "URLParam", "get", "url", "params", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L46-L48
train
DataDog/datadog-go
statsd/uds_blocking.go
newBlockingUdsWriter
func newBlockingUdsWriter(addr string) (*blockingUdsWriter, error) { udsAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return nil, err } // Defer connection to first Write writer := &blockingUdsWriter{addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout} return writer, nil }
go
func newBlockingUdsWriter(addr string) (*blockingUdsWriter, error) { udsAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return nil, err } // Defer connection to first Write writer := &blockingUdsWriter{addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout} return writer, nil }
[ "func", "newBlockingUdsWriter", "(", "addr", "string", ")", "(", "*", "blockingUdsWriter", ",", "error", ")", "{", "udsAddr", ",", "err", ":=", "net", ".", "ResolveUnixAddr", "(", "\"unixgram\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "re...
// New returns a pointer to a new blockingUdsWriter given a socket file path as addr.
[ "New", "returns", "a", "pointer", "to", "a", "new", "blockingUdsWriter", "given", "a", "socket", "file", "path", "as", "addr", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/uds_blocking.go#L21-L29
train
DataDog/datadog-go
statsd/statsd.go
format
func (c *Client) format(name string, value interface{}, suffix []byte, tags []string, rate float64) []byte { // preallocated buffer, stack allocated as long as it doesn't escape buf := make([]byte, 0, 200) if c.Namespace != "" { buf = append(buf, c.Namespace...) } buf = append(buf, name...) buf = append(buf, ':') switch val := value.(type) { case float64: buf = strconv.AppendFloat(buf, val, 'f', 6, 64) case int64: buf = strconv.AppendInt(buf, val, 10) case string: buf = append(buf, val...) default: // do nothing } buf = append(buf, suffix...) if rate < 1 { buf = append(buf, "|@"...) buf = strconv.AppendFloat(buf, rate, 'f', -1, 64) } buf = appendTagString(buf, c.Tags, tags) // non-zeroing copy to avoid referencing a larger than necessary underlying array return append([]byte(nil), buf...) }
go
func (c *Client) format(name string, value interface{}, suffix []byte, tags []string, rate float64) []byte { // preallocated buffer, stack allocated as long as it doesn't escape buf := make([]byte, 0, 200) if c.Namespace != "" { buf = append(buf, c.Namespace...) } buf = append(buf, name...) buf = append(buf, ':') switch val := value.(type) { case float64: buf = strconv.AppendFloat(buf, val, 'f', 6, 64) case int64: buf = strconv.AppendInt(buf, val, 10) case string: buf = append(buf, val...) default: // do nothing } buf = append(buf, suffix...) if rate < 1 { buf = append(buf, "|@"...) buf = strconv.AppendFloat(buf, rate, 'f', -1, 64) } buf = appendTagString(buf, c.Tags, tags) // non-zeroing copy to avoid referencing a larger than necessary underlying array return append([]byte(nil), buf...) }
[ "func", "(", "c", "*", "Client", ")", "format", "(", "name", "string", ",", "value", "interface", "{", "}", ",", "suffix", "[", "]", "byte", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "[", "]", "byte", "{", "buf", ":=", "make",...
// format a message from its name, value, tags and rate. Also adds global // namespace and tags.
[ "format", "a", "message", "from", "its", "name", "value", "tags", "and", "rate", ".", "Also", "adds", "global", "namespace", "and", "tags", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L184-L218
train
DataDog/datadog-go
statsd/statsd.go
SetWriteTimeout
func (c *Client) SetWriteTimeout(d time.Duration) error { if c == nil { return fmt.Errorf("Client is nil") } return c.writer.SetWriteTimeout(d) }
go
func (c *Client) SetWriteTimeout(d time.Duration) error { if c == nil { return fmt.Errorf("Client is nil") } return c.writer.SetWriteTimeout(d) }
[ "func", "(", "c", "*", "Client", ")", "SetWriteTimeout", "(", "d", "time", ".", "Duration", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Client is nil\"", ")", "\n", "}", "\n", "return", "c", ".", "writer", ...
// SetWriteTimeout allows the user to set a custom UDS write timeout. Not supported for UDP.
[ "SetWriteTimeout", "allows", "the", "user", "to", "set", "a", "custom", "UDS", "write", "timeout", ".", "Not", "supported", "for", "UDP", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L221-L226
train
DataDog/datadog-go
statsd/statsd.go
Flush
func (c *Client) Flush() error { if c == nil { return fmt.Errorf("Client is nil") } c.Lock() defer c.Unlock() return c.flushLocked() }
go
func (c *Client) Flush() error { if c == nil { return fmt.Errorf("Client is nil") } c.Lock() defer c.Unlock() return c.flushLocked() }
[ "func", "(", "c", "*", "Client", ")", "Flush", "(", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Client is nil\"", ")", "\n", "}", "\n", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "...
// Flush forces a flush of the pending commands in the buffer
[ "Flush", "forces", "a", "flush", "of", "the", "pending", "commands", "in", "the", "buffer" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L308-L315
train
DataDog/datadog-go
statsd/statsd.go
flushLocked
func (c *Client) flushLocked() error { frames, flushable := c.joinMaxSize(c.commands, "\n", OptimalPayloadSize) var err error cmdsFlushed := 0 for i, data := range frames { _, e := c.writer.Write(data) if e != nil { err = e break } cmdsFlushed += flushable[i] } // clear the slice with a slice op, doesn't realloc if cmdsFlushed == len(c.commands) { c.commands = c.commands[:0] } else { //this case will cause a future realloc... // drop problematic command though (sorry). c.commands = c.commands[cmdsFlushed+1:] } return err }
go
func (c *Client) flushLocked() error { frames, flushable := c.joinMaxSize(c.commands, "\n", OptimalPayloadSize) var err error cmdsFlushed := 0 for i, data := range frames { _, e := c.writer.Write(data) if e != nil { err = e break } cmdsFlushed += flushable[i] } // clear the slice with a slice op, doesn't realloc if cmdsFlushed == len(c.commands) { c.commands = c.commands[:0] } else { //this case will cause a future realloc... // drop problematic command though (sorry). c.commands = c.commands[cmdsFlushed+1:] } return err }
[ "func", "(", "c", "*", "Client", ")", "flushLocked", "(", ")", "error", "{", "frames", ",", "flushable", ":=", "c", ".", "joinMaxSize", "(", "c", ".", "commands", ",", "\"\\n\"", ",", "\\n", ")", "\n", "OptimalPayloadSize", "\n", "var", "err", "error",...
// flush the commands in the buffer. Lock must be held by caller.
[ "flush", "the", "commands", "in", "the", "buffer", ".", "Lock", "must", "be", "held", "by", "caller", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L318-L340
train
DataDog/datadog-go
statsd/statsd.go
send
func (c *Client) send(name string, value interface{}, suffix []byte, tags []string, rate float64) error { if c == nil { return fmt.Errorf("Client is nil") } if rate < 1 && rand.Float64() > rate { return nil } data := c.format(name, value, suffix, tags, rate) return c.sendMsg(data) }
go
func (c *Client) send(name string, value interface{}, suffix []byte, tags []string, rate float64) error { if c == nil { return fmt.Errorf("Client is nil") } if rate < 1 && rand.Float64() > rate { return nil } data := c.format(name, value, suffix, tags, rate) return c.sendMsg(data) }
[ "func", "(", "c", "*", "Client", ")", "send", "(", "name", "string", ",", "value", "interface", "{", "}", ",", "suffix", "[", "]", "byte", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "if", "c", "==", "nil", "{", ...
// send handles sampling and sends the message over UDP. It also adds global namespace prefixes and tags.
[ "send", "handles", "sampling", "and", "sends", "the", "message", "over", "UDP", ".", "It", "also", "adds", "global", "namespace", "prefixes", "and", "tags", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L362-L371
train
DataDog/datadog-go
statsd/statsd.go
Gauge
func (c *Client) Gauge(name string, value float64, tags []string, rate float64) error { return c.send(name, value, gaugeSuffix, tags, rate) }
go
func (c *Client) Gauge(name string, value float64, tags []string, rate float64) error { return c.send(name, value, gaugeSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Gauge", "(", "name", "string", ",", "value", "float64", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "value", ",", "gaugeSuffix", ",...
// Gauge measures the value of a metric at a particular time.
[ "Gauge", "measures", "the", "value", "of", "a", "metric", "at", "a", "particular", "time", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L374-L376
train
DataDog/datadog-go
statsd/statsd.go
Count
func (c *Client) Count(name string, value int64, tags []string, rate float64) error { return c.send(name, value, countSuffix, tags, rate) }
go
func (c *Client) Count(name string, value int64, tags []string, rate float64) error { return c.send(name, value, countSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Count", "(", "name", "string", ",", "value", "int64", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "value", ",", "countSuffix", ",",...
// Count tracks how many times something happened per second.
[ "Count", "tracks", "how", "many", "times", "something", "happened", "per", "second", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L379-L381
train
DataDog/datadog-go
statsd/statsd.go
Histogram
func (c *Client) Histogram(name string, value float64, tags []string, rate float64) error { return c.send(name, value, histogramSuffix, tags, rate) }
go
func (c *Client) Histogram(name string, value float64, tags []string, rate float64) error { return c.send(name, value, histogramSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Histogram", "(", "name", "string", ",", "value", "float64", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "value", ",", "histogramSuffi...
// Histogram tracks the statistical distribution of a set of values on each host.
[ "Histogram", "tracks", "the", "statistical", "distribution", "of", "a", "set", "of", "values", "on", "each", "host", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L384-L386
train
DataDog/datadog-go
statsd/statsd.go
Distribution
func (c *Client) Distribution(name string, value float64, tags []string, rate float64) error { return c.send(name, value, distributionSuffix, tags, rate) }
go
func (c *Client) Distribution(name string, value float64, tags []string, rate float64) error { return c.send(name, value, distributionSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Distribution", "(", "name", "string", ",", "value", "float64", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "value", ",", "distributio...
// Distribution tracks the statistical distribution of a set of values across your infrastructure.
[ "Distribution", "tracks", "the", "statistical", "distribution", "of", "a", "set", "of", "values", "across", "your", "infrastructure", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L389-L391
train
DataDog/datadog-go
statsd/statsd.go
Decr
func (c *Client) Decr(name string, tags []string, rate float64) error { return c.send(name, nil, decrSuffix, tags, rate) }
go
func (c *Client) Decr(name string, tags []string, rate float64) error { return c.send(name, nil, decrSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Decr", "(", "name", "string", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "nil", ",", "decrSuffix", ",", "tags", ",", "rate", ")"...
// Decr is just Count of -1
[ "Decr", "is", "just", "Count", "of", "-", "1" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L394-L396
train
DataDog/datadog-go
statsd/statsd.go
Incr
func (c *Client) Incr(name string, tags []string, rate float64) error { return c.send(name, nil, incrSuffix, tags, rate) }
go
func (c *Client) Incr(name string, tags []string, rate float64) error { return c.send(name, nil, incrSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Incr", "(", "name", "string", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "nil", ",", "incrSuffix", ",", "tags", ",", "rate", ")"...
// Incr is just Count of 1
[ "Incr", "is", "just", "Count", "of", "1" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L399-L401
train
DataDog/datadog-go
statsd/statsd.go
Set
func (c *Client) Set(name string, value string, tags []string, rate float64) error { return c.send(name, value, setSuffix, tags, rate) }
go
func (c *Client) Set(name string, value string, tags []string, rate float64) error { return c.send(name, value, setSuffix, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Set", "(", "name", "string", ",", "value", "string", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "send", "(", "name", ",", "value", ",", "setSuffix", ",", ...
// Set counts the number of unique elements in a group.
[ "Set", "counts", "the", "number", "of", "unique", "elements", "in", "a", "group", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L404-L406
train
DataDog/datadog-go
statsd/statsd.go
Timing
func (c *Client) Timing(name string, value time.Duration, tags []string, rate float64) error { return c.TimeInMilliseconds(name, value.Seconds()*1000, tags, rate) }
go
func (c *Client) Timing(name string, value time.Duration, tags []string, rate float64) error { return c.TimeInMilliseconds(name, value.Seconds()*1000, tags, rate) }
[ "func", "(", "c", "*", "Client", ")", "Timing", "(", "name", "string", ",", "value", "time", ".", "Duration", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "error", "{", "return", "c", ".", "TimeInMilliseconds", "(", "name", ",", "val...
// Timing sends timing information, it is an alias for TimeInMilliseconds
[ "Timing", "sends", "timing", "information", "it", "is", "an", "alias", "for", "TimeInMilliseconds" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L409-L411
train
DataDog/datadog-go
statsd/statsd.go
Event
func (c *Client) Event(e *Event) error { if c == nil { return fmt.Errorf("Client is nil") } stat, err := e.Encode(c.Tags...) if err != nil { return err } return c.sendMsg([]byte(stat)) }
go
func (c *Client) Event(e *Event) error { if c == nil { return fmt.Errorf("Client is nil") } stat, err := e.Encode(c.Tags...) if err != nil { return err } return c.sendMsg([]byte(stat)) }
[ "func", "(", "c", "*", "Client", ")", "Event", "(", "e", "*", "Event", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Client is nil\"", ")", "\n", "}", "\n", "stat", ",", "err", ":=", "e", ".", "Encode", ...
// Event sends the provided Event.
[ "Event", "sends", "the", "provided", "Event", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L420-L429
train
DataDog/datadog-go
statsd/statsd.go
SimpleEvent
func (c *Client) SimpleEvent(title, text string) error { e := NewEvent(title, text) return c.Event(e) }
go
func (c *Client) SimpleEvent(title, text string) error { e := NewEvent(title, text) return c.Event(e) }
[ "func", "(", "c", "*", "Client", ")", "SimpleEvent", "(", "title", ",", "text", "string", ")", "error", "{", "e", ":=", "NewEvent", "(", "title", ",", "text", ")", "\n", "return", "c", ".", "Event", "(", "e", ")", "\n", "}" ]
// SimpleEvent sends an event with the provided title and text.
[ "SimpleEvent", "sends", "an", "event", "with", "the", "provided", "title", "and", "text", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L432-L435
train
DataDog/datadog-go
statsd/statsd.go
ServiceCheck
func (c *Client) ServiceCheck(sc *ServiceCheck) error { if c == nil { return fmt.Errorf("Client is nil") } stat, err := sc.Encode(c.Tags...) if err != nil { return err } return c.sendMsg([]byte(stat)) }
go
func (c *Client) ServiceCheck(sc *ServiceCheck) error { if c == nil { return fmt.Errorf("Client is nil") } stat, err := sc.Encode(c.Tags...) if err != nil { return err } return c.sendMsg([]byte(stat)) }
[ "func", "(", "c", "*", "Client", ")", "ServiceCheck", "(", "sc", "*", "ServiceCheck", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Client is nil\"", ")", "\n", "}", "\n", "stat", ",", "err", ":=", "sc", "....
// ServiceCheck sends the provided ServiceCheck.
[ "ServiceCheck", "sends", "the", "provided", "ServiceCheck", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L438-L447
train
DataDog/datadog-go
statsd/statsd.go
SimpleServiceCheck
func (c *Client) SimpleServiceCheck(name string, status ServiceCheckStatus) error { sc := NewServiceCheck(name, status) return c.ServiceCheck(sc) }
go
func (c *Client) SimpleServiceCheck(name string, status ServiceCheckStatus) error { sc := NewServiceCheck(name, status) return c.ServiceCheck(sc) }
[ "func", "(", "c", "*", "Client", ")", "SimpleServiceCheck", "(", "name", "string", ",", "status", "ServiceCheckStatus", ")", "error", "{", "sc", ":=", "NewServiceCheck", "(", "name", ",", "status", ")", "\n", "return", "c", ".", "ServiceCheck", "(", "sc", ...
// SimpleServiceCheck sends an serviceCheck with the provided name and status.
[ "SimpleServiceCheck", "sends", "an", "serviceCheck", "with", "the", "provided", "name", "and", "status", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L450-L453
train
DataDog/datadog-go
statsd/statsd.go
Close
func (c *Client) Close() error { if c == nil { return fmt.Errorf("Client is nil") } select { case c.stop <- struct{}{}: default: } // if this client is buffered, flush before closing the writer if c.bufferLength > 0 { if err := c.Flush(); err != nil { return err } } return c.writer.Close() }
go
func (c *Client) Close() error { if c == nil { return fmt.Errorf("Client is nil") } select { case c.stop <- struct{}{}: default: } // if this client is buffered, flush before closing the writer if c.bufferLength > 0 { if err := c.Flush(); err != nil { return err } } return c.writer.Close() }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Client is nil\"", ")", "\n", "}", "\n", "select", "{", "case", "c", ".", "stop", "<-", "struct", "{", "}",...
// Close the client connection.
[ "Close", "the", "client", "connection", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L456-L473
train
DataDog/datadog-go
statsd/statsd.go
NewEvent
func NewEvent(title, text string) *Event { return &Event{ Title: title, Text: text, } }
go
func NewEvent(title, text string) *Event { return &Event{ Title: title, Text: text, } }
[ "func", "NewEvent", "(", "title", ",", "text", "string", ")", "*", "Event", "{", "return", "&", "Event", "{", "Title", ":", "title", ",", "Text", ":", "text", ",", "}", "\n", "}" ]
// NewEvent creates a new event with the given title and text. Error checking // against these values is done at send-time, or upon running e.Check.
[ "NewEvent", "creates", "a", "new", "event", "with", "the", "given", "title", "and", "text", ".", "Error", "checking", "against", "these", "values", "is", "done", "at", "send", "-", "time", "or", "upon", "running", "e", ".", "Check", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L529-L534
train
DataDog/datadog-go
statsd/statsd.go
Encode
func (e Event) Encode(tags ...string) (string, error) { err := e.Check() if err != nil { return "", err } text := e.escapedText() var buffer bytes.Buffer buffer.WriteString("_e{") buffer.WriteString(strconv.FormatInt(int64(len(e.Title)), 10)) buffer.WriteRune(',') buffer.WriteString(strconv.FormatInt(int64(len(text)), 10)) buffer.WriteString("}:") buffer.WriteString(e.Title) buffer.WriteRune('|') buffer.WriteString(text) if !e.Timestamp.IsZero() { buffer.WriteString("|d:") buffer.WriteString(strconv.FormatInt(int64(e.Timestamp.Unix()), 10)) } if len(e.Hostname) != 0 { buffer.WriteString("|h:") buffer.WriteString(e.Hostname) } if len(e.AggregationKey) != 0 { buffer.WriteString("|k:") buffer.WriteString(e.AggregationKey) } if len(e.Priority) != 0 { buffer.WriteString("|p:") buffer.WriteString(string(e.Priority)) } if len(e.SourceTypeName) != 0 { buffer.WriteString("|s:") buffer.WriteString(e.SourceTypeName) } if len(e.AlertType) != 0 { buffer.WriteString("|t:") buffer.WriteString(string(e.AlertType)) } writeTagString(&buffer, tags, e.Tags) return buffer.String(), nil }
go
func (e Event) Encode(tags ...string) (string, error) { err := e.Check() if err != nil { return "", err } text := e.escapedText() var buffer bytes.Buffer buffer.WriteString("_e{") buffer.WriteString(strconv.FormatInt(int64(len(e.Title)), 10)) buffer.WriteRune(',') buffer.WriteString(strconv.FormatInt(int64(len(text)), 10)) buffer.WriteString("}:") buffer.WriteString(e.Title) buffer.WriteRune('|') buffer.WriteString(text) if !e.Timestamp.IsZero() { buffer.WriteString("|d:") buffer.WriteString(strconv.FormatInt(int64(e.Timestamp.Unix()), 10)) } if len(e.Hostname) != 0 { buffer.WriteString("|h:") buffer.WriteString(e.Hostname) } if len(e.AggregationKey) != 0 { buffer.WriteString("|k:") buffer.WriteString(e.AggregationKey) } if len(e.Priority) != 0 { buffer.WriteString("|p:") buffer.WriteString(string(e.Priority)) } if len(e.SourceTypeName) != 0 { buffer.WriteString("|s:") buffer.WriteString(e.SourceTypeName) } if len(e.AlertType) != 0 { buffer.WriteString("|t:") buffer.WriteString(string(e.AlertType)) } writeTagString(&buffer, tags, e.Tags) return buffer.String(), nil }
[ "func", "(", "e", "Event", ")", "Encode", "(", "tags", "...", "string", ")", "(", "string", ",", "error", ")", "{", "err", ":=", "e", ".", "Check", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", ...
// Encode returns the dogstatsd wire protocol representation for an event. // Tags may be passed which will be added to the encoded output but not to // the Event's list of tags, eg. for default tags.
[ "Encode", "returns", "the", "dogstatsd", "wire", "protocol", "representation", "for", "an", "event", ".", "Tags", "may", "be", "passed", "which", "will", "be", "added", "to", "the", "encoded", "output", "but", "not", "to", "the", "Event", "s", "list", "of"...
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L550-L601
train
DataDog/datadog-go
statsd/statsd.go
NewServiceCheck
func NewServiceCheck(name string, status ServiceCheckStatus) *ServiceCheck { return &ServiceCheck{ Name: name, Status: status, } }
go
func NewServiceCheck(name string, status ServiceCheckStatus) *ServiceCheck { return &ServiceCheck{ Name: name, Status: status, } }
[ "func", "NewServiceCheck", "(", "name", "string", ",", "status", "ServiceCheckStatus", ")", "*", "ServiceCheck", "{", "return", "&", "ServiceCheck", "{", "Name", ":", "name", ",", "Status", ":", "status", ",", "}", "\n", "}" ]
// NewServiceCheck creates a new serviceCheck with the given name and status. Error checking // against these values is done at send-time, or upon running sc.Check.
[ "NewServiceCheck", "creates", "a", "new", "serviceCheck", "with", "the", "given", "name", "and", "status", ".", "Error", "checking", "against", "these", "values", "is", "done", "at", "send", "-", "time", "or", "upon", "running", "sc", ".", "Check", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L636-L641
train
DataDog/datadog-go
statsd/statsd.go
Encode
func (sc ServiceCheck) Encode(tags ...string) (string, error) { err := sc.Check() if err != nil { return "", err } message := sc.escapedMessage() var buffer bytes.Buffer buffer.WriteString("_sc|") buffer.WriteString(sc.Name) buffer.WriteRune('|') buffer.WriteString(strconv.FormatInt(int64(sc.Status), 10)) if !sc.Timestamp.IsZero() { buffer.WriteString("|d:") buffer.WriteString(strconv.FormatInt(int64(sc.Timestamp.Unix()), 10)) } if len(sc.Hostname) != 0 { buffer.WriteString("|h:") buffer.WriteString(sc.Hostname) } writeTagString(&buffer, tags, sc.Tags) if len(message) != 0 { buffer.WriteString("|m:") buffer.WriteString(message) } return buffer.String(), nil }
go
func (sc ServiceCheck) Encode(tags ...string) (string, error) { err := sc.Check() if err != nil { return "", err } message := sc.escapedMessage() var buffer bytes.Buffer buffer.WriteString("_sc|") buffer.WriteString(sc.Name) buffer.WriteRune('|') buffer.WriteString(strconv.FormatInt(int64(sc.Status), 10)) if !sc.Timestamp.IsZero() { buffer.WriteString("|d:") buffer.WriteString(strconv.FormatInt(int64(sc.Timestamp.Unix()), 10)) } if len(sc.Hostname) != 0 { buffer.WriteString("|h:") buffer.WriteString(sc.Hostname) } writeTagString(&buffer, tags, sc.Tags) if len(message) != 0 { buffer.WriteString("|m:") buffer.WriteString(message) } return buffer.String(), nil }
[ "func", "(", "sc", "ServiceCheck", ")", "Encode", "(", "tags", "...", "string", ")", "(", "string", ",", "error", ")", "{", "err", ":=", "sc", ".", "Check", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", ...
// Encode returns the dogstatsd wire protocol representation for an serviceCheck. // Tags may be passed which will be added to the encoded output but not to // the Event's list of tags, eg. for default tags.
[ "Encode", "returns", "the", "dogstatsd", "wire", "protocol", "representation", "for", "an", "serviceCheck", ".", "Tags", "may", "be", "passed", "which", "will", "be", "added", "to", "the", "encoded", "output", "but", "not", "to", "the", "Event", "s", "list",...
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L657-L688
train
DataDog/datadog-go
statsd/uds_async.go
newAsyncUdsWriter
func newAsyncUdsWriter(addr string) (*asyncUdsWriter, error) { udsAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return nil, err } writer := &asyncUdsWriter{ addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout, // 8192 * 8KB = 65.5MB datagramQueue: make(chan []byte, 8192), stopChan: make(chan struct{}, 1), } go writer.sendLoop() return writer, nil }
go
func newAsyncUdsWriter(addr string) (*asyncUdsWriter, error) { udsAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return nil, err } writer := &asyncUdsWriter{ addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout, // 8192 * 8KB = 65.5MB datagramQueue: make(chan []byte, 8192), stopChan: make(chan struct{}, 1), } go writer.sendLoop() return writer, nil }
[ "func", "newAsyncUdsWriter", "(", "addr", "string", ")", "(", "*", "asyncUdsWriter", ",", "error", ")", "{", "udsAddr", ",", "err", ":=", "net", ".", "ResolveUnixAddr", "(", "\"unixgram\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return",...
// New returns a pointer to a new asyncUdsWriter given a socket file path as addr.
[ "New", "returns", "a", "pointer", "to", "a", "new", "asyncUdsWriter", "given", "a", "socket", "file", "path", "as", "addr", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/uds_async.go#L23-L40
train
DataDog/datadog-go
statsd/uds_async.go
SetWriteTimeout
func (w *asyncUdsWriter) SetWriteTimeout(d time.Duration) error { w.writeTimeout = d return nil }
go
func (w *asyncUdsWriter) SetWriteTimeout(d time.Duration) error { w.writeTimeout = d return nil }
[ "func", "(", "w", "*", "asyncUdsWriter", ")", "SetWriteTimeout", "(", "d", "time", ".", "Duration", ")", "error", "{", "w", ".", "writeTimeout", "=", "d", "\n", "return", "nil", "\n", "}" ]
// SetWriteTimeout allows the user to set a custom write timeout
[ "SetWriteTimeout", "allows", "the", "user", "to", "set", "a", "custom", "write", "timeout" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/uds_async.go#L54-L57
train
DataDog/datadog-go
statsd/udp.go
Write
func (w *udpWriter) Write(data []byte) (int, error) { return w.conn.Write(data) }
go
func (w *udpWriter) Write(data []byte) (int, error) { return w.conn.Write(data) }
[ "func", "(", "w", "*", "udpWriter", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "w", ".", "conn", ".", "Write", "(", "data", ")", "\n", "}" ]
// Write data to the UDP connection with no error handling
[ "Write", "data", "to", "the", "UDP", "connection", "with", "no", "error", "handling" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/udp.go#L49-L51
train
DataDog/datadog-go
statsd/options.go
WithNamespace
func WithNamespace(namespace string) Option { return func(o *Options) error { o.Namespace = namespace return nil } }
go
func WithNamespace(namespace string) Option { return func(o *Options) error { o.Namespace = namespace return nil } }
[ "func", "WithNamespace", "(", "namespace", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "Namespace", "=", "namespace", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithNamespace sets the Namespace option.
[ "WithNamespace", "sets", "the", "Namespace", "option", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/options.go#L64-L69
train
DataDog/datadog-go
statsd/options.go
WithTags
func WithTags(tags []string) Option { return func(o *Options) error { o.Tags = tags return nil } }
go
func WithTags(tags []string) Option { return func(o *Options) error { o.Tags = tags return nil } }
[ "func", "WithTags", "(", "tags", "[", "]", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "Tags", "=", "tags", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithTags sets the Tags option.
[ "WithTags", "sets", "the", "Tags", "option", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/options.go#L72-L77
train
DataDog/datadog-go
statsd/options.go
WithMaxMessagesPerPayload
func WithMaxMessagesPerPayload(maxMessagesPerPayload int) Option { return func(o *Options) error { o.MaxMessagesPerPayload = maxMessagesPerPayload return nil } }
go
func WithMaxMessagesPerPayload(maxMessagesPerPayload int) Option { return func(o *Options) error { o.MaxMessagesPerPayload = maxMessagesPerPayload return nil } }
[ "func", "WithMaxMessagesPerPayload", "(", "maxMessagesPerPayload", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "MaxMessagesPerPayload", "=", "maxMessagesPerPayload", "\n", "return", "nil", "\n", "}", "\n", ...
// WithMaxMessagesPerPayload sets the MaxMessagesPerPayload option.
[ "WithMaxMessagesPerPayload", "sets", "the", "MaxMessagesPerPayload", "option", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/options.go#L88-L93
train
DataDog/datadog-go
statsd/options.go
WithWriteTimeoutUDS
func WithWriteTimeoutUDS(writeTimeoutUDS time.Duration) Option { return func(o *Options) error { o.WriteTimeoutUDS = writeTimeoutUDS return nil } }
go
func WithWriteTimeoutUDS(writeTimeoutUDS time.Duration) Option { return func(o *Options) error { o.WriteTimeoutUDS = writeTimeoutUDS return nil } }
[ "func", "WithWriteTimeoutUDS", "(", "writeTimeoutUDS", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "WriteTimeoutUDS", "=", "writeTimeoutUDS", "\n", "return", "nil", "\n", "}", "\n", ...
// WithWriteTimeoutUDS sets the WriteTimeoutUDS option.
[ "WithWriteTimeoutUDS", "sets", "the", "WriteTimeoutUDS", "option", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/options.go#L104-L109
train
google/go-jsonnet
vm.go
MakeVM
func MakeVM() *VM { return &VM{ MaxStack: 500, ext: make(vmExtMap), tla: make(vmExtMap), nativeFuncs: make(map[string]*NativeFunction), ErrorFormatter: &termErrorFormatter{pretty: false, maxStackTraceSize: 20}, importer: &FileImporter{}, } }
go
func MakeVM() *VM { return &VM{ MaxStack: 500, ext: make(vmExtMap), tla: make(vmExtMap), nativeFuncs: make(map[string]*NativeFunction), ErrorFormatter: &termErrorFormatter{pretty: false, maxStackTraceSize: 20}, importer: &FileImporter{}, } }
[ "func", "MakeVM", "(", ")", "*", "VM", "{", "return", "&", "VM", "{", "MaxStack", ":", "500", ",", "ext", ":", "make", "(", "vmExtMap", ")", ",", "tla", ":", "make", "(", "vmExtMap", ")", ",", "nativeFuncs", ":", "make", "(", "map", "[", "string"...
// MakeVM creates a new VM with default parameters.
[ "MakeVM", "creates", "a", "new", "VM", "with", "default", "parameters", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L55-L64
train
google/go-jsonnet
vm.go
ExtVar
func (vm *VM) ExtVar(key string, val string) { vm.ext[key] = vmExt{value: val, isCode: false} }
go
func (vm *VM) ExtVar(key string, val string) { vm.ext[key] = vmExt{value: val, isCode: false} }
[ "func", "(", "vm", "*", "VM", ")", "ExtVar", "(", "key", "string", ",", "val", "string", ")", "{", "vm", ".", "ext", "[", "key", "]", "=", "vmExt", "{", "value", ":", "val", ",", "isCode", ":", "false", "}", "\n", "}" ]
// ExtVar binds a Jsonnet external var to the given value.
[ "ExtVar", "binds", "a", "Jsonnet", "external", "var", "to", "the", "given", "value", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L67-L69
train
google/go-jsonnet
vm.go
ExtCode
func (vm *VM) ExtCode(key string, val string) { vm.ext[key] = vmExt{value: val, isCode: true} }
go
func (vm *VM) ExtCode(key string, val string) { vm.ext[key] = vmExt{value: val, isCode: true} }
[ "func", "(", "vm", "*", "VM", ")", "ExtCode", "(", "key", "string", ",", "val", "string", ")", "{", "vm", ".", "ext", "[", "key", "]", "=", "vmExt", "{", "value", ":", "val", ",", "isCode", ":", "true", "}", "\n", "}" ]
// ExtCode binds a Jsonnet external code var to the given code.
[ "ExtCode", "binds", "a", "Jsonnet", "external", "code", "var", "to", "the", "given", "code", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L72-L74
train
google/go-jsonnet
vm.go
TLAVar
func (vm *VM) TLAVar(key string, val string) { vm.tla[key] = vmExt{value: val, isCode: false} }
go
func (vm *VM) TLAVar(key string, val string) { vm.tla[key] = vmExt{value: val, isCode: false} }
[ "func", "(", "vm", "*", "VM", ")", "TLAVar", "(", "key", "string", ",", "val", "string", ")", "{", "vm", ".", "tla", "[", "key", "]", "=", "vmExt", "{", "value", ":", "val", ",", "isCode", ":", "false", "}", "\n", "}" ]
// TLAVar binds a Jsonnet top level argument to the given value.
[ "TLAVar", "binds", "a", "Jsonnet", "top", "level", "argument", "to", "the", "given", "value", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L77-L79
train
google/go-jsonnet
vm.go
TLACode
func (vm *VM) TLACode(key string, val string) { vm.tla[key] = vmExt{value: val, isCode: true} }
go
func (vm *VM) TLACode(key string, val string) { vm.tla[key] = vmExt{value: val, isCode: true} }
[ "func", "(", "vm", "*", "VM", ")", "TLACode", "(", "key", "string", ",", "val", "string", ")", "{", "vm", ".", "tla", "[", "key", "]", "=", "vmExt", "{", "value", ":", "val", ",", "isCode", ":", "true", "}", "\n", "}" ]
// TLACode binds a Jsonnet top level argument to the given code.
[ "TLACode", "binds", "a", "Jsonnet", "top", "level", "argument", "to", "the", "given", "code", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L82-L84
train
google/go-jsonnet
vm.go
NativeFunction
func (vm *VM) NativeFunction(f *NativeFunction) { vm.nativeFuncs[f.Name] = f }
go
func (vm *VM) NativeFunction(f *NativeFunction) { vm.nativeFuncs[f.Name] = f }
[ "func", "(", "vm", "*", "VM", ")", "NativeFunction", "(", "f", "*", "NativeFunction", ")", "{", "vm", ".", "nativeFuncs", "[", "f", ".", "Name", "]", "=", "f", "\n", "}" ]
// NativeFunction registers a native function.
[ "NativeFunction", "registers", "a", "native", "function", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L151-L153
train
google/go-jsonnet
vm.go
EvaluateSnippet
func (vm *VM) EvaluateSnippet(filename string, snippet string) (json string, formattedErr error) { output, err := vm.evaluateSnippet(filename, snippet, evalKindRegular) if err != nil { return "", errors.New(vm.ErrorFormatter.Format(err)) } json = output.(string) return }
go
func (vm *VM) EvaluateSnippet(filename string, snippet string) (json string, formattedErr error) { output, err := vm.evaluateSnippet(filename, snippet, evalKindRegular) if err != nil { return "", errors.New(vm.ErrorFormatter.Format(err)) } json = output.(string) return }
[ "func", "(", "vm", "*", "VM", ")", "EvaluateSnippet", "(", "filename", "string", ",", "snippet", "string", ")", "(", "json", "string", ",", "formattedErr", "error", ")", "{", "output", ",", "err", ":=", "vm", ".", "evaluateSnippet", "(", "filename", ",",...
// EvaluateSnippet evaluates a string containing Jsonnet code, return a JSON // string. // // The filename parameter is only used for error messages.
[ "EvaluateSnippet", "evaluates", "a", "string", "containing", "Jsonnet", "code", "return", "a", "JSON", "string", ".", "The", "filename", "parameter", "is", "only", "used", "for", "error", "messages", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L159-L166
train
google/go-jsonnet
vm.go
EvaluateSnippetStream
func (vm *VM) EvaluateSnippetStream(filename string, snippet string) (docs []string, formattedErr error) { output, err := vm.evaluateSnippet(filename, snippet, evalKindStream) if err != nil { return nil, errors.New(vm.ErrorFormatter.Format(err)) } docs = output.([]string) return }
go
func (vm *VM) EvaluateSnippetStream(filename string, snippet string) (docs []string, formattedErr error) { output, err := vm.evaluateSnippet(filename, snippet, evalKindStream) if err != nil { return nil, errors.New(vm.ErrorFormatter.Format(err)) } docs = output.([]string) return }
[ "func", "(", "vm", "*", "VM", ")", "EvaluateSnippetStream", "(", "filename", "string", ",", "snippet", "string", ")", "(", "docs", "[", "]", "string", ",", "formattedErr", "error", ")", "{", "output", ",", "err", ":=", "vm", ".", "evaluateSnippet", "(", ...
// EvaluateSnippetStream evaluates a string containing Jsonnet code to an array. // The array is returned as an array of JSON strings. // // The filename parameter is only used for error messages.
[ "EvaluateSnippetStream", "evaluates", "a", "string", "containing", "Jsonnet", "code", "to", "an", "array", ".", "The", "array", "is", "returned", "as", "an", "array", "of", "JSON", "strings", ".", "The", "filename", "parameter", "is", "only", "used", "for", ...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L172-L179
train
google/go-jsonnet
vm.go
EvaluateSnippetMulti
func (vm *VM) EvaluateSnippetMulti(filename string, snippet string) (files map[string]string, formattedErr error) { output, err := vm.evaluateSnippet(filename, snippet, evalKindMulti) if err != nil { return nil, errors.New(vm.ErrorFormatter.Format(err)) } files = output.(map[string]string) return }
go
func (vm *VM) EvaluateSnippetMulti(filename string, snippet string) (files map[string]string, formattedErr error) { output, err := vm.evaluateSnippet(filename, snippet, evalKindMulti) if err != nil { return nil, errors.New(vm.ErrorFormatter.Format(err)) } files = output.(map[string]string) return }
[ "func", "(", "vm", "*", "VM", ")", "EvaluateSnippetMulti", "(", "filename", "string", ",", "snippet", "string", ")", "(", "files", "map", "[", "string", "]", "string", ",", "formattedErr", "error", ")", "{", "output", ",", "err", ":=", "vm", ".", "eval...
// EvaluateSnippetMulti evaluates a string containing Jsonnet code to key-value // pairs. The keys are field name strings and the values are JSON strings. // // The filename parameter is only used for error messages.
[ "EvaluateSnippetMulti", "evaluates", "a", "string", "containing", "Jsonnet", "code", "to", "key", "-", "value", "pairs", ".", "The", "keys", "are", "field", "name", "strings", "and", "the", "values", "are", "JSON", "strings", ".", "The", "filename", "parameter...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L185-L192
train
google/go-jsonnet
vm.go
SnippetToAST
func SnippetToAST(filename string, snippet string) (ast.Node, error) { return snippetToAST(filename, snippet) }
go
func SnippetToAST(filename string, snippet string) (ast.Node, error) { return snippetToAST(filename, snippet) }
[ "func", "SnippetToAST", "(", "filename", "string", ",", "snippet", "string", ")", "(", "ast", ".", "Node", ",", "error", ")", "{", "return", "snippetToAST", "(", "filename", ",", "snippet", ")", "\n", "}" ]
// SnippetToAST parses a snippet and returns the resulting AST.
[ "SnippetToAST", "parses", "a", "snippet", "and", "returns", "the", "resulting", "AST", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/vm.go#L219-L221
train
google/go-jsonnet
value.go
findField
func findField(curr value, minSuperDepth int, f string) (bool, simpleObjectField, bindingFrame, int) { switch curr := curr.(type) { case *valueExtendedObject: if curr.right.inheritanceSize() > minSuperDepth { found, field, frame, counter := findField(curr.right, minSuperDepth, f) if found { return true, field, frame, counter } } found, field, frame, counter := findField(curr.left, minSuperDepth-curr.right.inheritanceSize(), f) return found, field, frame, counter + curr.right.inheritanceSize() case *valueSimpleObject: if minSuperDepth <= 0 { if field, ok := curr.fields[f]; ok { return true, field, curr.upValues, 0 } } return false, simpleObjectField{}, nil, 0 default: panic(fmt.Sprintf("Unknown object type %#v", curr)) } }
go
func findField(curr value, minSuperDepth int, f string) (bool, simpleObjectField, bindingFrame, int) { switch curr := curr.(type) { case *valueExtendedObject: if curr.right.inheritanceSize() > minSuperDepth { found, field, frame, counter := findField(curr.right, minSuperDepth, f) if found { return true, field, frame, counter } } found, field, frame, counter := findField(curr.left, minSuperDepth-curr.right.inheritanceSize(), f) return found, field, frame, counter + curr.right.inheritanceSize() case *valueSimpleObject: if minSuperDepth <= 0 { if field, ok := curr.fields[f]; ok { return true, field, curr.upValues, 0 } } return false, simpleObjectField{}, nil, 0 default: panic(fmt.Sprintf("Unknown object type %#v", curr)) } }
[ "func", "findField", "(", "curr", "value", ",", "minSuperDepth", "int", ",", "f", "string", ")", "(", "bool", ",", "simpleObjectField", ",", "bindingFrame", ",", "int", ")", "{", "switch", "curr", ":=", "curr", ".", "(", "type", ")", "{", "case", "*", ...
// findField returns a field in object curr, with superDepth at least minSuperDepth // It also returns an associated bindingFrame and actual superDepth that the field // was found at.
[ "findField", "returns", "a", "field", "in", "object", "curr", "with", "superDepth", "at", "least", "minSuperDepth", "It", "also", "returns", "an", "associated", "bindingFrame", "and", "actual", "superDepth", "that", "the", "field", "was", "found", "at", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/value.go#L582-L604
train
google/go-jsonnet
dump/utils.go
deInterface
func deInterface(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v }
go
func deInterface(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v }
[ "func", "deInterface", "(", "v", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "&&", "!", "v", ".", "IsNil", "(", ")", "{", "v", "=", "v", ".", "Elem", "(", ")",...
// deInterface returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface.
[ "deInterface", "returns", "values", "inside", "of", "non", "-", "nil", "interfaces", "when", "possible", ".", "This", "is", "useful", "for", "data", "types", "like", "structs", "arrays", "slices", "and", "maps", "which", "can", "contain", "varying", "types", ...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/dump/utils.go#L69-L74
train
google/go-jsonnet
parser/static_error.go
MakeStaticError
func MakeStaticError(msg string, lr ast.LocationRange) StaticError { return StaticError{Msg: msg, Loc: lr} }
go
func MakeStaticError(msg string, lr ast.LocationRange) StaticError { return StaticError{Msg: msg, Loc: lr} }
[ "func", "MakeStaticError", "(", "msg", "string", ",", "lr", "ast", ".", "LocationRange", ")", "StaticError", "{", "return", "StaticError", "{", "Msg", ":", "msg", ",", "Loc", ":", "lr", "}", "\n", "}" ]
// MakeStaticError returns a StaticError with a message and a LocationRange.
[ "MakeStaticError", "returns", "a", "StaticError", "with", "a", "message", "and", "a", "LocationRange", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/static_error.go#L41-L43
train
google/go-jsonnet
parser/static_error.go
Error
func (err StaticError) Error() string { loc := "" if err.Loc.IsSet() { loc = err.Loc.String() } return fmt.Sprintf("%v %v", loc, err.Msg) }
go
func (err StaticError) Error() string { loc := "" if err.Loc.IsSet() { loc = err.Loc.String() } return fmt.Sprintf("%v %v", loc, err.Msg) }
[ "func", "(", "err", "StaticError", ")", "Error", "(", ")", "string", "{", "loc", ":=", "\"\"", "\n", "if", "err", ".", "Loc", ".", "IsSet", "(", ")", "{", "loc", "=", "err", ".", "Loc", ".", "String", "(", ")", "\n", "}", "\n", "return", "fmt",...
// Error returns the string representation of a StaticError.
[ "Error", "returns", "the", "string", "representation", "of", "a", "StaticError", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/static_error.go#L46-L52
train
google/go-jsonnet
linter/linter.go
Lint
func Lint(node ast.Node, e *ErrorWriter) { lintingInfo := LintingInfo{ variables: nil, } std := variable{ name: "std", declNode: nil, uses: nil, param: false, } findVariables(node, &lintingInfo, vScope{"std": &std}) for _, v := range lintingInfo.variables { if len(v.uses) == 0 && !v.param { e.writeError(parser.MakeStaticError("Unused variable: "+string(v.name), *v.declNode.Loc())) } } }
go
func Lint(node ast.Node, e *ErrorWriter) { lintingInfo := LintingInfo{ variables: nil, } std := variable{ name: "std", declNode: nil, uses: nil, param: false, } findVariables(node, &lintingInfo, vScope{"std": &std}) for _, v := range lintingInfo.variables { if len(v.uses) == 0 && !v.param { e.writeError(parser.MakeStaticError("Unused variable: "+string(v.name), *v.declNode.Loc())) } } }
[ "func", "Lint", "(", "node", "ast", ".", "Node", ",", "e", "*", "ErrorWriter", ")", "{", "lintingInfo", ":=", "LintingInfo", "{", "variables", ":", "nil", ",", "}", "\n", "std", ":=", "variable", "{", "name", ":", "\"std\"", ",", "declNode", ":", "ni...
// Lint analyses a node and reports any issues it encounters to an error writer.
[ "Lint", "analyses", "a", "node", "and", "reports", "any", "issues", "it", "encounters", "to", "an", "error", "writer", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/linter/linter.go#L39-L55
train
google/go-jsonnet
imports.go
MakeImportCache
func MakeImportCache(importer Importer) *ImportCache { return &ImportCache{ importer: importer, foundAtVerification: make(map[string]Contents), codeCache: make(map[string]potentialValue), } }
go
func MakeImportCache(importer Importer) *ImportCache { return &ImportCache{ importer: importer, foundAtVerification: make(map[string]Contents), codeCache: make(map[string]potentialValue), } }
[ "func", "MakeImportCache", "(", "importer", "Importer", ")", "*", "ImportCache", "{", "return", "&", "ImportCache", "{", "importer", ":", "importer", ",", "foundAtVerification", ":", "make", "(", "map", "[", "string", "]", "Contents", ")", ",", "codeCache", ...
// MakeImportCache creates an ImportCache using an Importer.
[ "MakeImportCache", "creates", "an", "ImportCache", "using", "an", "Importer", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/imports.go#L77-L83
train
google/go-jsonnet
imports.go
ImportString
func (cache *ImportCache) ImportString(importedFrom, importedPath string, i *interpreter, trace TraceElement) (*valueString, error) { data, _, err := cache.importData(importedFrom, importedPath) if err != nil { return nil, i.Error(err.Error(), trace) } return makeValueString(data.String()), nil }
go
func (cache *ImportCache) ImportString(importedFrom, importedPath string, i *interpreter, trace TraceElement) (*valueString, error) { data, _, err := cache.importData(importedFrom, importedPath) if err != nil { return nil, i.Error(err.Error(), trace) } return makeValueString(data.String()), nil }
[ "func", "(", "cache", "*", "ImportCache", ")", "ImportString", "(", "importedFrom", ",", "importedPath", "string", ",", "i", "*", "interpreter", ",", "trace", "TraceElement", ")", "(", "*", "valueString", ",", "error", ")", "{", "data", ",", "_", ",", "e...
// ImportString imports a string, caches it and then returns it.
[ "ImportString", "imports", "a", "string", "caches", "it", "and", "then", "returns", "it", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/imports.go#L101-L107
train
google/go-jsonnet
imports.go
ImportCode
func (cache *ImportCache) ImportCode(importedFrom, importedPath string, i *interpreter, trace TraceElement) (value, error) { contents, foundAt, err := cache.importData(importedFrom, importedPath) if err != nil { return nil, i.Error(err.Error(), trace) } var pv potentialValue if cachedPV, isCached := cache.codeCache[foundAt]; !isCached { // File hasn't been parsed and analyzed before, update the cache record. pv = codeToPV(i, foundAt, contents.String()) cache.codeCache[foundAt] = pv } else { pv = cachedPV } return i.evaluatePV(pv, trace) }
go
func (cache *ImportCache) ImportCode(importedFrom, importedPath string, i *interpreter, trace TraceElement) (value, error) { contents, foundAt, err := cache.importData(importedFrom, importedPath) if err != nil { return nil, i.Error(err.Error(), trace) } var pv potentialValue if cachedPV, isCached := cache.codeCache[foundAt]; !isCached { // File hasn't been parsed and analyzed before, update the cache record. pv = codeToPV(i, foundAt, contents.String()) cache.codeCache[foundAt] = pv } else { pv = cachedPV } return i.evaluatePV(pv, trace) }
[ "func", "(", "cache", "*", "ImportCache", ")", "ImportCode", "(", "importedFrom", ",", "importedPath", "string", ",", "i", "*", "interpreter", ",", "trace", "TraceElement", ")", "(", "value", ",", "error", ")", "{", "contents", ",", "foundAt", ",", "err", ...
// ImportCode imports code from a path.
[ "ImportCode", "imports", "code", "from", "a", "path", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/imports.go#L128-L142
train
google/go-jsonnet
imports.go
Import
func (importer *FileImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error) { dir, _ := path.Split(importedFrom) found, content, foundHere, err := importer.tryPath(dir, importedPath) if err != nil { return Contents{}, "", err } for i := len(importer.JPaths) - 1; !found && i >= 0; i-- { found, content, foundHere, err = importer.tryPath(importer.JPaths[i], importedPath) if err != nil { return Contents{}, "", err } } if !found { return Contents{}, "", fmt.Errorf("couldn't open import %#v: no match locally or in the Jsonnet library paths", importedPath) } return content, foundHere, nil }
go
func (importer *FileImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error) { dir, _ := path.Split(importedFrom) found, content, foundHere, err := importer.tryPath(dir, importedPath) if err != nil { return Contents{}, "", err } for i := len(importer.JPaths) - 1; !found && i >= 0; i-- { found, content, foundHere, err = importer.tryPath(importer.JPaths[i], importedPath) if err != nil { return Contents{}, "", err } } if !found { return Contents{}, "", fmt.Errorf("couldn't open import %#v: no match locally or in the Jsonnet library paths", importedPath) } return content, foundHere, nil }
[ "func", "(", "importer", "*", "FileImporter", ")", "Import", "(", "importedFrom", ",", "importedPath", "string", ")", "(", "contents", "Contents", ",", "foundAt", "string", ",", "err", "error", ")", "{", "dir", ",", "_", ":=", "path", ".", "Split", "(", ...
// Import imports file from the filesystem.
[ "Import", "imports", "file", "from", "the", "filesystem", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/imports.go#L193-L211
train
google/go-jsonnet
imports.go
Import
func (importer *MemoryImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error) { if content, ok := importer.Data[importedPath]; ok { return content, importedPath, nil } return Contents{}, "", fmt.Errorf("import not available %v", importedPath) }
go
func (importer *MemoryImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error) { if content, ok := importer.Data[importedPath]; ok { return content, importedPath, nil } return Contents{}, "", fmt.Errorf("import not available %v", importedPath) }
[ "func", "(", "importer", "*", "MemoryImporter", ")", "Import", "(", "importedFrom", ",", "importedPath", "string", ")", "(", "contents", "Contents", ",", "foundAt", "string", ",", "err", "error", ")", "{", "if", "content", ",", "ok", ":=", "importer", ".",...
// Import fetches data from a map entry. // All paths are treated as absolute keys.
[ "Import", "fetches", "data", "from", "a", "map", "entry", ".", "All", "paths", "are", "treated", "as", "absolute", "keys", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/imports.go#L220-L225
train
google/go-jsonnet
cmd/jsonnet/cmd.go
writeOutputStream
func writeOutputStream(output []string, outputFile string) error { var f *os.File if outputFile == "" { f = os.Stdout } else { var err error f, err = os.Create(outputFile) if err != nil { return err } defer f.Close() } for _, doc := range output { _, err := f.WriteString("---\n") if err != nil { return err } _, err = f.WriteString(doc) if err != nil { return err } } if len(output) > 0 { _, err := f.WriteString("...\n") if err != nil { return err } } return nil }
go
func writeOutputStream(output []string, outputFile string) error { var f *os.File if outputFile == "" { f = os.Stdout } else { var err error f, err = os.Create(outputFile) if err != nil { return err } defer f.Close() } for _, doc := range output { _, err := f.WriteString("---\n") if err != nil { return err } _, err = f.WriteString(doc) if err != nil { return err } } if len(output) > 0 { _, err := f.WriteString("...\n") if err != nil { return err } } return nil }
[ "func", "writeOutputStream", "(", "output", "[", "]", "string", ",", "outputFile", "string", ")", "error", "{", "var", "f", "*", "os", ".", "File", "\n", "if", "outputFile", "==", "\"\"", "{", "f", "=", "os", ".", "Stdout", "\n", "}", "else", "{", ...
// writeOutputStream writes the output as a YAML stream.
[ "writeOutputStream", "writes", "the", "output", "as", "a", "YAML", "stream", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/cmd/jsonnet/cmd.go#L442-L475
train
google/go-jsonnet
parser/lexer.go
checkWhitespace
func checkWhitespace(a, b string) int { i := 0 for ; i < len(a); i++ { if a[i] != ' ' && a[i] != '\t' { // a has run out of whitespace and b matched up to this point. Return // result. return i } if i >= len(b) { // We ran off the edge of b while a still has whitespace. Return 0 as // failure. return 0 } if a[i] != b[i] { // a has whitespace but b does not. Return 0 as failure. return 0 } } // We ran off the end of a and b kept up return i }
go
func checkWhitespace(a, b string) int { i := 0 for ; i < len(a); i++ { if a[i] != ' ' && a[i] != '\t' { // a has run out of whitespace and b matched up to this point. Return // result. return i } if i >= len(b) { // We ran off the edge of b while a still has whitespace. Return 0 as // failure. return 0 } if a[i] != b[i] { // a has whitespace but b does not. Return 0 as failure. return 0 } } // We ran off the end of a and b kept up return i }
[ "func", "checkWhitespace", "(", "a", ",", "b", "string", ")", "int", "{", "i", ":=", "0", "\n", "for", ";", "i", "<", "len", "(", "a", ")", ";", "i", "++", "{", "if", "a", "[", "i", "]", "!=", "' '", "&&", "a", "[", "i", "]", "!=", "'\\t'...
// Check that b has at least the same whitespace prefix as a and returns the // amount of this whitespace, otherwise returns 0. If a has no whitespace // prefix than return 0.
[ "Check", "that", "b", "has", "at", "least", "the", "same", "whitespace", "prefix", "as", "a", "and", "returns", "the", "amount", "of", "this", "whitespace", "otherwise", "returns", "0", ".", "If", "a", "has", "no", "whitespace", "prefix", "than", "return",...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L235-L255
train
google/go-jsonnet
parser/lexer.go
backup
func (l *lexer) backup() { if l.prev.byteNo == lexEOF { panic("backup called with no valid previous rune") } l.pos = l.prev l.prev = position{byteNo: lexEOF} }
go
func (l *lexer) backup() { if l.prev.byteNo == lexEOF { panic("backup called with no valid previous rune") } l.pos = l.prev l.prev = position{byteNo: lexEOF} }
[ "func", "(", "l", "*", "lexer", ")", "backup", "(", ")", "{", "if", "l", ".", "prev", ".", "byteNo", "==", "lexEOF", "{", "panic", "(", "\"backup called with no valid previous rune\"", ")", "\n", "}", "\n", "l", ".", "pos", "=", "l", ".", "prev", "\n...
// backup steps back one rune. Can only be called once per call of next. // It also does not recover the previous value of freshLine.
[ "backup", "steps", "back", "one", "rune", ".", "Can", "only", "be", "called", "once", "per", "call", "of", "next", ".", "It", "also", "does", "not", "recover", "the", "previous", "value", "of", "freshLine", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L335-L341
train
google/go-jsonnet
parser/lexer.go
resetTokenStart
func (l *lexer) resetTokenStart() { l.tokenStart = l.pos.byteNo l.tokenStartLoc = l.location() }
go
func (l *lexer) resetTokenStart() { l.tokenStart = l.pos.byteNo l.tokenStartLoc = l.location() }
[ "func", "(", "l", "*", "lexer", ")", "resetTokenStart", "(", ")", "{", "l", ".", "tokenStart", "=", "l", ".", "pos", ".", "byteNo", "\n", "l", ".", "tokenStartLoc", "=", "l", ".", "location", "(", ")", "\n", "}" ]
// Reset the current working token start to the current cursor position. This // may throw away some characters. This does not throw away any accumulated // fodder.
[ "Reset", "the", "current", "working", "token", "start", "to", "the", "current", "cursor", "position", ".", "This", "may", "throw", "away", "some", "characters", ".", "This", "does", "not", "throw", "away", "any", "accumulated", "fodder", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L361-L364
train
google/go-jsonnet
parser/lexer.go
lexWhitespace
func (l *lexer) lexWhitespace() (int, int) { r := l.next() indent := 0 newLines := 0 for ; isWhitespace(r); r = l.next() { switch r { case '\r': // Ignore. break case '\n': indent = 0 newLines++ break case ' ': indent++ break // This only works for \t at the beginning of lines, but we strip it everywhere else // anyway. The only case where this will cause a problem is spaces followed by \t // at the beginning of a line. However that is rare, ill-advised, and if re-indentation // is enabled it will be fixed later. case '\t': indent += 8 break } } l.backup() return newLines, indent }
go
func (l *lexer) lexWhitespace() (int, int) { r := l.next() indent := 0 newLines := 0 for ; isWhitespace(r); r = l.next() { switch r { case '\r': // Ignore. break case '\n': indent = 0 newLines++ break case ' ': indent++ break // This only works for \t at the beginning of lines, but we strip it everywhere else // anyway. The only case where this will cause a problem is spaces followed by \t // at the beginning of a line. However that is rare, ill-advised, and if re-indentation // is enabled it will be fixed later. case '\t': indent += 8 break } } l.backup() return newLines, indent }
[ "func", "(", "l", "*", "lexer", ")", "lexWhitespace", "(", ")", "(", "int", ",", "int", ")", "{", "r", ":=", "l", ".", "next", "(", ")", "\n", "indent", ":=", "0", "\n", "newLines", ":=", "0", "\n", "for", ";", "isWhitespace", "(", "r", ")", ...
// lexWhitespace consumes all whitespace and returns the number of \n and number of // spaces after last \n. It also converts \t to spaces. // The parameter 'r' is the rune that begins the whitespace.
[ "lexWhitespace", "consumes", "all", "whitespace", "and", "returns", "the", "number", "of", "\\", "n", "and", "number", "of", "spaces", "after", "last", "\\", "n", ".", "It", "also", "converts", "\\", "t", "to", "spaces", ".", "The", "parameter", "r", "is...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L395-L425
train
google/go-jsonnet
parser/lexer.go
lexUntilNewline
func (l *lexer) lexUntilNewline() (string, int, int) { // Compute 'text'. var buf bytes.Buffer lastNonSpace := 0 for r := l.next(); r != lexEOF && r != '\n'; r = l.next() { buf.WriteRune(r) if !isHorizontalWhitespace(r) { lastNonSpace = buf.Len() } } l.backup() // Trim whitespace off the end. buf.Truncate(lastNonSpace) text := buf.String() // Consume the '\n' and following indent. var newLines int newLines, indent := l.lexWhitespace() blanks := 0 if newLines > 0 { blanks = newLines - 1 } return text, blanks, indent }
go
func (l *lexer) lexUntilNewline() (string, int, int) { // Compute 'text'. var buf bytes.Buffer lastNonSpace := 0 for r := l.next(); r != lexEOF && r != '\n'; r = l.next() { buf.WriteRune(r) if !isHorizontalWhitespace(r) { lastNonSpace = buf.Len() } } l.backup() // Trim whitespace off the end. buf.Truncate(lastNonSpace) text := buf.String() // Consume the '\n' and following indent. var newLines int newLines, indent := l.lexWhitespace() blanks := 0 if newLines > 0 { blanks = newLines - 1 } return text, blanks, indent }
[ "func", "(", "l", "*", "lexer", ")", "lexUntilNewline", "(", ")", "(", "string", ",", "int", ",", "int", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "lastNonSpace", ":=", "0", "\n", "for", "r", ":=", "l", ".", "next", "(", ")", ";", "...
// lexUntilNewLine consumes all text until the end of the line and returns the // number of newlines after that as well as the next indent.
[ "lexUntilNewLine", "consumes", "all", "text", "until", "the", "end", "of", "the", "line", "and", "returns", "the", "number", "of", "newlines", "after", "that", "as", "well", "as", "the", "next", "indent", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L429-L452
train
google/go-jsonnet
parser/lexer.go
lexNumber
func (l *lexer) lexNumber() error { // This function should be understood with reference to the linked image: // http://www.json.org/number.gif // Note, we deviate from the json.org documentation as follows: // There is no reason to lex negative numbers as atomic tokens, it is better to parse them // as a unary operator combined with a numeric literal. This avoids x-1 being tokenized as // <identifier> <number> instead of the intended <identifier> <binop> <number>. type numLexState int const ( numBegin numLexState = iota numAfterZero numAfterOneToNine numAfterDot numAfterDigit numAfterE numAfterExpSign numAfterExpDigit ) state := numBegin outerLoop: for true { r := l.next() switch state { case numBegin: switch { case r == '0': state = numAfterZero case r >= '1' && r <= '9': state = numAfterOneToNine default: // The caller should ensure the first rune is a digit. panic("Couldn't lex number") } case numAfterZero: switch r { case '.': state = numAfterDot case 'e', 'E': state = numAfterE default: break outerLoop } case numAfterOneToNine: switch { case r == '.': state = numAfterDot case r == 'e' || r == 'E': state = numAfterE case r >= '0' && r <= '9': state = numAfterOneToNine default: break outerLoop } case numAfterDot: switch { case r >= '0' && r <= '9': state = numAfterDigit default: return l.makeStaticErrorPoint( fmt.Sprintf("Couldn't lex number, junk after decimal point: %v", strconv.QuoteRuneToASCII(r)), l.prevLocation()) } case numAfterDigit: switch { case r == 'e' || r == 'E': state = numAfterE case r >= '0' && r <= '9': state = numAfterDigit default: break outerLoop } case numAfterE: switch { case r == '+' || r == '-': state = numAfterExpSign case r >= '0' && r <= '9': state = numAfterExpDigit default: return l.makeStaticErrorPoint( fmt.Sprintf("Couldn't lex number, junk after 'E': %v", strconv.QuoteRuneToASCII(r)), l.prevLocation()) } case numAfterExpSign: if r >= '0' && r <= '9' { state = numAfterExpDigit } else { return l.makeStaticErrorPoint( fmt.Sprintf("Couldn't lex number, junk after exponent sign: %v", strconv.QuoteRuneToASCII(r)), l.prevLocation()) } case numAfterExpDigit: if r >= '0' && r <= '9' { state = numAfterExpDigit } else { break outerLoop } } } l.backup() l.emitToken(tokenNumber) return nil }
go
func (l *lexer) lexNumber() error { // This function should be understood with reference to the linked image: // http://www.json.org/number.gif // Note, we deviate from the json.org documentation as follows: // There is no reason to lex negative numbers as atomic tokens, it is better to parse them // as a unary operator combined with a numeric literal. This avoids x-1 being tokenized as // <identifier> <number> instead of the intended <identifier> <binop> <number>. type numLexState int const ( numBegin numLexState = iota numAfterZero numAfterOneToNine numAfterDot numAfterDigit numAfterE numAfterExpSign numAfterExpDigit ) state := numBegin outerLoop: for true { r := l.next() switch state { case numBegin: switch { case r == '0': state = numAfterZero case r >= '1' && r <= '9': state = numAfterOneToNine default: // The caller should ensure the first rune is a digit. panic("Couldn't lex number") } case numAfterZero: switch r { case '.': state = numAfterDot case 'e', 'E': state = numAfterE default: break outerLoop } case numAfterOneToNine: switch { case r == '.': state = numAfterDot case r == 'e' || r == 'E': state = numAfterE case r >= '0' && r <= '9': state = numAfterOneToNine default: break outerLoop } case numAfterDot: switch { case r >= '0' && r <= '9': state = numAfterDigit default: return l.makeStaticErrorPoint( fmt.Sprintf("Couldn't lex number, junk after decimal point: %v", strconv.QuoteRuneToASCII(r)), l.prevLocation()) } case numAfterDigit: switch { case r == 'e' || r == 'E': state = numAfterE case r >= '0' && r <= '9': state = numAfterDigit default: break outerLoop } case numAfterE: switch { case r == '+' || r == '-': state = numAfterExpSign case r >= '0' && r <= '9': state = numAfterExpDigit default: return l.makeStaticErrorPoint( fmt.Sprintf("Couldn't lex number, junk after 'E': %v", strconv.QuoteRuneToASCII(r)), l.prevLocation()) } case numAfterExpSign: if r >= '0' && r <= '9' { state = numAfterExpDigit } else { return l.makeStaticErrorPoint( fmt.Sprintf("Couldn't lex number, junk after exponent sign: %v", strconv.QuoteRuneToASCII(r)), l.prevLocation()) } case numAfterExpDigit: if r >= '0' && r <= '9' { state = numAfterExpDigit } else { break outerLoop } } } l.backup() l.emitToken(tokenNumber) return nil }
[ "func", "(", "l", "*", "lexer", ")", "lexNumber", "(", ")", "error", "{", "type", "numLexState", "int", "\n", "const", "(", "numBegin", "numLexState", "=", "iota", "\n", "numAfterZero", "\n", "numAfterOneToNine", "\n", "numAfterDot", "\n", "numAfterDigit", "...
// lexNumber will consume a number and emit a token. It is assumed // that the next rune to be served by the lexer will be a leading digit.
[ "lexNumber", "will", "consume", "a", "number", "and", "emit", "a", "token", ".", "It", "is", "assumed", "that", "the", "next", "rune", "to", "be", "served", "by", "the", "lexer", "will", "be", "a", "leading", "digit", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L456-L563
train
google/go-jsonnet
parser/lexer.go
lexIdentifier
func (l *lexer) lexIdentifier() { r := l.next() if !isIdentifierFirst(r) { panic("Unexpected character in lexIdentifier") } for ; r != lexEOF; r = l.next() { if !isIdentifier(r) { break } } l.backup() switch l.input[l.tokenStart:l.pos.byteNo] { case "assert": l.emitToken(tokenAssert) case "else": l.emitToken(tokenElse) case "error": l.emitToken(tokenError) case "false": l.emitToken(tokenFalse) case "for": l.emitToken(tokenFor) case "function": l.emitToken(tokenFunction) case "if": l.emitToken(tokenIf) case "import": l.emitToken(tokenImport) case "importstr": l.emitToken(tokenImportStr) case "in": l.emitToken(tokenIn) case "local": l.emitToken(tokenLocal) case "null": l.emitToken(tokenNullLit) case "self": l.emitToken(tokenSelf) case "super": l.emitToken(tokenSuper) case "tailstrict": l.emitToken(tokenTailStrict) case "then": l.emitToken(tokenThen) case "true": l.emitToken(tokenTrue) default: // Not a keyword, assume it is an identifier l.emitToken(tokenIdentifier) } }
go
func (l *lexer) lexIdentifier() { r := l.next() if !isIdentifierFirst(r) { panic("Unexpected character in lexIdentifier") } for ; r != lexEOF; r = l.next() { if !isIdentifier(r) { break } } l.backup() switch l.input[l.tokenStart:l.pos.byteNo] { case "assert": l.emitToken(tokenAssert) case "else": l.emitToken(tokenElse) case "error": l.emitToken(tokenError) case "false": l.emitToken(tokenFalse) case "for": l.emitToken(tokenFor) case "function": l.emitToken(tokenFunction) case "if": l.emitToken(tokenIf) case "import": l.emitToken(tokenImport) case "importstr": l.emitToken(tokenImportStr) case "in": l.emitToken(tokenIn) case "local": l.emitToken(tokenLocal) case "null": l.emitToken(tokenNullLit) case "self": l.emitToken(tokenSelf) case "super": l.emitToken(tokenSuper) case "tailstrict": l.emitToken(tokenTailStrict) case "then": l.emitToken(tokenThen) case "true": l.emitToken(tokenTrue) default: // Not a keyword, assume it is an identifier l.emitToken(tokenIdentifier) } }
[ "func", "(", "l", "*", "lexer", ")", "lexIdentifier", "(", ")", "{", "r", ":=", "l", ".", "next", "(", ")", "\n", "if", "!", "isIdentifierFirst", "(", "r", ")", "{", "panic", "(", "\"Unexpected character in lexIdentifier\"", ")", "\n", "}", "\n", "for"...
// lexIdentifier will consume a identifer and emit a token. It is assumed // that the next rune to be served by the lexer will be a leading digit. This // may emit a keyword or an identifier.
[ "lexIdentifier", "will", "consume", "a", "identifer", "and", "emit", "a", "token", ".", "It", "is", "assumed", "that", "the", "next", "rune", "to", "be", "served", "by", "the", "lexer", "will", "be", "a", "leading", "digit", ".", "This", "may", "emit", ...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/lexer.go#L568-L619
train
google/go-jsonnet
thunks.go
EvalCall
func (native *NativeFunction) EvalCall(arguments callArguments, i *interpreter, trace TraceElement) (value, error) { flatArgs := flattenArgs(arguments, native.Parameters()) nativeArgs := make([]interface{}, 0, len(flatArgs)) for _, arg := range flatArgs { v, err := i.evaluatePV(arg, trace) if err != nil { return nil, err } json, err := i.manifestJSON(trace, v) if err != nil { return nil, err } nativeArgs = append(nativeArgs, json) } resultJSON, err := native.Func(nativeArgs) if err != nil { return nil, i.Error(err.Error(), trace) } return jsonToValue(i, trace, resultJSON) }
go
func (native *NativeFunction) EvalCall(arguments callArguments, i *interpreter, trace TraceElement) (value, error) { flatArgs := flattenArgs(arguments, native.Parameters()) nativeArgs := make([]interface{}, 0, len(flatArgs)) for _, arg := range flatArgs { v, err := i.evaluatePV(arg, trace) if err != nil { return nil, err } json, err := i.manifestJSON(trace, v) if err != nil { return nil, err } nativeArgs = append(nativeArgs, json) } resultJSON, err := native.Func(nativeArgs) if err != nil { return nil, i.Error(err.Error(), trace) } return jsonToValue(i, trace, resultJSON) }
[ "func", "(", "native", "*", "NativeFunction", ")", "EvalCall", "(", "arguments", "callArguments", ",", "i", "*", "interpreter", ",", "trace", "TraceElement", ")", "(", "value", ",", "error", ")", "{", "flatArgs", ":=", "flattenArgs", "(", "arguments", ",", ...
// EvalCall evaluates a call to a NativeFunction and returns the result.
[ "EvalCall", "evaluates", "a", "call", "to", "a", "NativeFunction", "and", "returns", "the", "result", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/thunks.go#L242-L261
train
google/go-jsonnet
ast/util.go
AddIdentifiers
func (i IdentifierSet) AddIdentifiers(idents Identifiers) { for _, ident := range idents { i.Add(ident) } }
go
func (i IdentifierSet) AddIdentifiers(idents Identifiers) { for _, ident := range idents { i.Add(ident) } }
[ "func", "(", "i", "IdentifierSet", ")", "AddIdentifiers", "(", "idents", "Identifiers", ")", "{", "for", "_", ",", "ident", ":=", "range", "idents", "{", "i", ".", "Add", "(", "ident", ")", "\n", "}", "\n", "}" ]
// AddIdentifiers adds a slice of identifiers to an identifier set.
[ "AddIdentifiers", "adds", "a", "slice", "of", "identifiers", "to", "an", "identifier", "set", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/util.go#L22-L26
train
google/go-jsonnet
ast/util.go
ToOrderedSlice
func (i IdentifierSet) ToOrderedSlice() []Identifier { var s []Identifier for v := range i { s = append(s, v) } sort.Sort(identifierSorter(s)) return s }
go
func (i IdentifierSet) ToOrderedSlice() []Identifier { var s []Identifier for v := range i { s = append(s, v) } sort.Sort(identifierSorter(s)) return s }
[ "func", "(", "i", "IdentifierSet", ")", "ToOrderedSlice", "(", ")", "[", "]", "Identifier", "{", "var", "s", "[", "]", "Identifier", "\n", "for", "v", ":=", "range", "i", "{", "s", "=", "append", "(", "s", ",", "v", ")", "\n", "}", "\n", "sort", ...
// ToOrderedSlice returns the elements of the current set as an ordered slice.
[ "ToOrderedSlice", "returns", "the", "elements", "of", "the", "current", "set", "as", "an", "ordered", "slice", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/util.go#L29-L36
train
google/go-jsonnet
ast/identifier_set.go
NewIdentifierSet
func NewIdentifierSet(a ...Identifier) IdentifierSet { s := make(IdentifierSet) for _, i := range a { s.Add(i) } return s }
go
func NewIdentifierSet(a ...Identifier) IdentifierSet { s := make(IdentifierSet) for _, i := range a { s.Add(i) } return s }
[ "func", "NewIdentifierSet", "(", "a", "...", "Identifier", ")", "IdentifierSet", "{", "s", ":=", "make", "(", "IdentifierSet", ")", "\n", "for", "_", ",", "i", ":=", "range", "a", "{", "s", ".", "Add", "(", "i", ")", "\n", "}", "\n", "return", "s",...
// NewIdentifierSet creates and returns a reference to an empty set.
[ "NewIdentifierSet", "creates", "and", "returns", "a", "reference", "to", "an", "empty", "set", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/identifier_set.go#L15-L21
train
google/go-jsonnet
ast/identifier_set.go
Iter
func (set IdentifierSet) Iter() <-chan Identifier { ch := make(chan Identifier) go func() { for elem := range set { ch <- elem } close(ch) }() return ch }
go
func (set IdentifierSet) Iter() <-chan Identifier { ch := make(chan Identifier) go func() { for elem := range set { ch <- elem } close(ch) }() return ch }
[ "func", "(", "set", "IdentifierSet", ")", "Iter", "(", ")", "<-", "chan", "Identifier", "{", "ch", ":=", "make", "(", "chan", "Identifier", ")", "\n", "go", "func", "(", ")", "{", "for", "elem", ":=", "range", "set", "{", "ch", "<-", "elem", "\n", ...
// Iter returns a channel of type identifier that you can range over.
[ "Iter", "returns", "a", "channel", "of", "type", "identifier", "that", "you", "can", "range", "over", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/identifier_set.go#L137-L147
train
google/go-jsonnet
parser/context.go
Children
func Children(node ast.Node) []ast.Node { var result []ast.Node result = append(result, directChildren(node)...) result = append(result, thunkChildren(node)...) result = append(result, specialChildren(node)...) return result }
go
func Children(node ast.Node) []ast.Node { var result []ast.Node result = append(result, directChildren(node)...) result = append(result, thunkChildren(node)...) result = append(result, specialChildren(node)...) return result }
[ "func", "Children", "(", "node", "ast", ".", "Node", ")", "[", "]", "ast", ".", "Node", "{", "var", "result", "[", "]", "ast", ".", "Node", "\n", "result", "=", "append", "(", "result", ",", "directChildren", "(", "node", ")", "...", ")", "\n", "...
// Children returns all children of a node. It supports ASTs before and after desugaring.
[ "Children", "returns", "all", "children", "of", "a", "node", ".", "It", "supports", "ASTs", "before", "and", "after", "desugaring", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/context.go#L339-L345
train
google/go-jsonnet
ast/fodder.go
MakeFodderElement
func MakeFodderElement(kind FodderKind, blanks int, indent int, comment []string) FodderElement { if kind == FodderLineEnd && len(comment) > 1 { panic(fmt.Sprintf("FodderLineEnd but comment == %v.", comment)) } if kind == FodderInterstitial && blanks > 0 { panic(fmt.Sprintf("FodderInterstitial but blanks == %d", blanks)) } if kind == FodderInterstitial && indent > 0 { panic(fmt.Sprintf("FodderInterstitial but indent == %d", blanks)) } if kind == FodderInterstitial && len(comment) != 1 { panic(fmt.Sprintf("FodderInterstitial but comment == %v.", comment)) } if kind == FodderParagraph && len(comment) == 0 { panic(fmt.Sprintf("FodderParagraph but comment was empty")) } return FodderElement{Kind: kind, Blanks: blanks, Indent: indent, Comment: comment} }
go
func MakeFodderElement(kind FodderKind, blanks int, indent int, comment []string) FodderElement { if kind == FodderLineEnd && len(comment) > 1 { panic(fmt.Sprintf("FodderLineEnd but comment == %v.", comment)) } if kind == FodderInterstitial && blanks > 0 { panic(fmt.Sprintf("FodderInterstitial but blanks == %d", blanks)) } if kind == FodderInterstitial && indent > 0 { panic(fmt.Sprintf("FodderInterstitial but indent == %d", blanks)) } if kind == FodderInterstitial && len(comment) != 1 { panic(fmt.Sprintf("FodderInterstitial but comment == %v.", comment)) } if kind == FodderParagraph && len(comment) == 0 { panic(fmt.Sprintf("FodderParagraph but comment was empty")) } return FodderElement{Kind: kind, Blanks: blanks, Indent: indent, Comment: comment} }
[ "func", "MakeFodderElement", "(", "kind", "FodderKind", ",", "blanks", "int", ",", "indent", "int", ",", "comment", "[", "]", "string", ")", "FodderElement", "{", "if", "kind", "==", "FodderLineEnd", "&&", "len", "(", "comment", ")", ">", "1", "{", "pani...
// MakeFodderElement is a helper function that checks some preconditions.
[ "MakeFodderElement", "is", "a", "helper", "function", "that", "checks", "some", "preconditions", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L76-L93
train
google/go-jsonnet
ast/fodder.go
FodderHasCleanEndline
func FodderHasCleanEndline(fodder Fodder) bool { return len(fodder) > 0 && fodder[len(fodder)-1].Kind != FodderInterstitial }
go
func FodderHasCleanEndline(fodder Fodder) bool { return len(fodder) > 0 && fodder[len(fodder)-1].Kind != FodderInterstitial }
[ "func", "FodderHasCleanEndline", "(", "fodder", "Fodder", ")", "bool", "{", "return", "len", "(", "fodder", ")", ">", "0", "&&", "fodder", "[", "len", "(", "fodder", ")", "-", "1", "]", ".", "Kind", "!=", "FodderInterstitial", "\n", "}" ]
// FodderHasCleanEndline is true if the fodder doesn't end with an interstitial.
[ "FodderHasCleanEndline", "is", "true", "if", "the", "fodder", "doesn", "t", "end", "with", "an", "interstitial", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L100-L102
train
google/go-jsonnet
ast/fodder.go
FodderAppend
func FodderAppend(a *Fodder, elem FodderElement) { if FodderHasCleanEndline(*a) && elem.Kind == FodderLineEnd { if len(elem.Comment) > 0 { // The line end had a comment, so create a single line paragraph for it. *a = append(*a, MakeFodderElement(FodderParagraph, elem.Blanks, elem.Indent, elem.Comment)) } else { back := &(*a)[len(*a)-1] // Merge it into the previous line end. back.Indent = elem.Indent back.Blanks += elem.Blanks } } else { if !FodderHasCleanEndline(*a) && elem.Kind == FodderParagraph { *a = append(*a, MakeFodderElement(FodderLineEnd, 0, elem.Indent, []string{})) } *a = append(*a, elem) } }
go
func FodderAppend(a *Fodder, elem FodderElement) { if FodderHasCleanEndline(*a) && elem.Kind == FodderLineEnd { if len(elem.Comment) > 0 { // The line end had a comment, so create a single line paragraph for it. *a = append(*a, MakeFodderElement(FodderParagraph, elem.Blanks, elem.Indent, elem.Comment)) } else { back := &(*a)[len(*a)-1] // Merge it into the previous line end. back.Indent = elem.Indent back.Blanks += elem.Blanks } } else { if !FodderHasCleanEndline(*a) && elem.Kind == FodderParagraph { *a = append(*a, MakeFodderElement(FodderLineEnd, 0, elem.Indent, []string{})) } *a = append(*a, elem) } }
[ "func", "FodderAppend", "(", "a", "*", "Fodder", ",", "elem", "FodderElement", ")", "{", "if", "FodderHasCleanEndline", "(", "*", "a", ")", "&&", "elem", ".", "Kind", "==", "FodderLineEnd", "{", "if", "len", "(", "elem", ".", "Comment", ")", ">", "0", ...
// FodderAppend appends to the fodder but preserves constraints. // // See FodderConcat below.
[ "FodderAppend", "appends", "to", "the", "fodder", "but", "preserves", "constraints", ".", "See", "FodderConcat", "below", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L107-L124
train
google/go-jsonnet
ast/fodder.go
FodderConcat
func FodderConcat(a Fodder, b Fodder) Fodder { if len(a) == 0 { return b } if len(b) == 0 { return a } r := a // Carefully add the first element of b. FodderAppend(&r, b[0]) // Add the rest of b. for i := 1; i < len(b); i++ { r = append(r, b[i]) } return r }
go
func FodderConcat(a Fodder, b Fodder) Fodder { if len(a) == 0 { return b } if len(b) == 0 { return a } r := a // Carefully add the first element of b. FodderAppend(&r, b[0]) // Add the rest of b. for i := 1; i < len(b); i++ { r = append(r, b[i]) } return r }
[ "func", "FodderConcat", "(", "a", "Fodder", ",", "b", "Fodder", ")", "Fodder", "{", "if", "len", "(", "a", ")", "==", "0", "{", "return", "b", "\n", "}", "\n", "if", "len", "(", "b", ")", "==", "0", "{", "return", "a", "\n", "}", "\n", "r", ...
// FodderConcat concats the two fodders but also preserves constraints. // // Namely, a FodderLineEnd is not allowed to follow a FodderParagraph or a FodderLineEnd.
[ "FodderConcat", "concats", "the", "two", "fodders", "but", "also", "preserves", "constraints", ".", "Namely", "a", "FodderLineEnd", "is", "not", "allowed", "to", "follow", "a", "FodderParagraph", "or", "a", "FodderLineEnd", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L129-L144
train
google/go-jsonnet
ast/fodder.go
FodderMoveFront
func FodderMoveFront(a *Fodder, b *Fodder) { *a = FodderConcat(*b, *a) *b = Fodder{} }
go
func FodderMoveFront(a *Fodder, b *Fodder) { *a = FodderConcat(*b, *a) *b = Fodder{} }
[ "func", "FodderMoveFront", "(", "a", "*", "Fodder", ",", "b", "*", "Fodder", ")", "{", "*", "a", "=", "FodderConcat", "(", "*", "b", ",", "*", "a", ")", "\n", "*", "b", "=", "Fodder", "{", "}", "\n", "}" ]
// FodderMoveFront moves b to the front of a.
[ "FodderMoveFront", "moves", "b", "to", "the", "front", "of", "a", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L147-L150
train
google/go-jsonnet
ast/fodder.go
FodderEnsureCleanNewline
func FodderEnsureCleanNewline(fodder *Fodder) { if !FodderHasCleanEndline(*fodder) { FodderAppend(fodder, MakeFodderElement(FodderLineEnd, 0, 0, []string{})) } }
go
func FodderEnsureCleanNewline(fodder *Fodder) { if !FodderHasCleanEndline(*fodder) { FodderAppend(fodder, MakeFodderElement(FodderLineEnd, 0, 0, []string{})) } }
[ "func", "FodderEnsureCleanNewline", "(", "fodder", "*", "Fodder", ")", "{", "if", "!", "FodderHasCleanEndline", "(", "*", "fodder", ")", "{", "FodderAppend", "(", "fodder", ",", "MakeFodderElement", "(", "FodderLineEnd", ",", "0", ",", "0", ",", "[", "]", ...
// FodderEnsureCleanNewline adds a LineEnd to the fodder if necessary.
[ "FodderEnsureCleanNewline", "adds", "a", "LineEnd", "to", "the", "fodder", "if", "necessary", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L153-L157
train
google/go-jsonnet
ast/fodder.go
FodderElementCountNewlines
func FodderElementCountNewlines(elem FodderElement) int { switch elem.Kind { case FodderInterstitial: return 0 case FodderLineEnd: return 1 case FodderParagraph: return len(elem.Comment) + elem.Blanks } panic(fmt.Sprintf("Unknown FodderElement kind %d", elem.Kind)) }
go
func FodderElementCountNewlines(elem FodderElement) int { switch elem.Kind { case FodderInterstitial: return 0 case FodderLineEnd: return 1 case FodderParagraph: return len(elem.Comment) + elem.Blanks } panic(fmt.Sprintf("Unknown FodderElement kind %d", elem.Kind)) }
[ "func", "FodderElementCountNewlines", "(", "elem", "FodderElement", ")", "int", "{", "switch", "elem", ".", "Kind", "{", "case", "FodderInterstitial", ":", "return", "0", "\n", "case", "FodderLineEnd", ":", "return", "1", "\n", "case", "FodderParagraph", ":", ...
// FodderElementCountNewlines returns the number of new line chars represented by the fodder element
[ "FodderElementCountNewlines", "returns", "the", "number", "of", "new", "line", "chars", "represented", "by", "the", "fodder", "element" ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L160-L170
train
google/go-jsonnet
ast/fodder.go
FodderCountNewlines
func FodderCountNewlines(fodder Fodder) int { sum := 0 for _, elem := range fodder { sum += FodderElementCountNewlines(elem) } return sum }
go
func FodderCountNewlines(fodder Fodder) int { sum := 0 for _, elem := range fodder { sum += FodderElementCountNewlines(elem) } return sum }
[ "func", "FodderCountNewlines", "(", "fodder", "Fodder", ")", "int", "{", "sum", ":=", "0", "\n", "for", "_", ",", "elem", ":=", "range", "fodder", "{", "sum", "+=", "FodderElementCountNewlines", "(", "elem", ")", "\n", "}", "\n", "return", "sum", "\n", ...
// FodderCountNewlines returns the number of new line chars represented by the fodder.
[ "FodderCountNewlines", "returns", "the", "number", "of", "new", "line", "chars", "represented", "by", "the", "fodder", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/ast/fodder.go#L173-L179
train
google/go-jsonnet
parser/literalfield_set.go
NewLiteralFieldSet
func NewLiteralFieldSet(a ...LiteralField) LiteralFieldSet { s := make(LiteralFieldSet) for _, i := range a { s.Add(i) } return s }
go
func NewLiteralFieldSet(a ...LiteralField) LiteralFieldSet { s := make(LiteralFieldSet) for _, i := range a { s.Add(i) } return s }
[ "func", "NewLiteralFieldSet", "(", "a", "...", "LiteralField", ")", "LiteralFieldSet", "{", "s", ":=", "make", "(", "LiteralFieldSet", ")", "\n", "for", "_", ",", "i", ":=", "range", "a", "{", "s", ".", "Add", "(", "i", ")", "\n", "}", "\n", "return"...
// NewLiteralFieldSet creates and returns a reference to an empty set.
[ "NewLiteralFieldSet", "creates", "and", "returns", "a", "reference", "to", "an", "empty", "set", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/literalfield_set.go#L15-L21
train
google/go-jsonnet
parser/literalfield_set.go
Iter
func (set LiteralFieldSet) Iter() <-chan LiteralField { ch := make(chan LiteralField) go func() { for elem := range set { ch <- elem } close(ch) }() return ch }
go
func (set LiteralFieldSet) Iter() <-chan LiteralField { ch := make(chan LiteralField) go func() { for elem := range set { ch <- elem } close(ch) }() return ch }
[ "func", "(", "set", "LiteralFieldSet", ")", "Iter", "(", ")", "<-", "chan", "LiteralField", "{", "ch", ":=", "make", "(", "chan", "LiteralField", ")", "\n", "go", "func", "(", ")", "{", "for", "elem", ":=", "range", "set", "{", "ch", "<-", "elem", ...
// Iter returns a channel of type LiteralField that you can range over.
[ "Iter", "returns", "a", "channel", "of", "type", "LiteralField", "that", "you", "can", "range", "over", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/literalfield_set.go#L137-L147
train
google/go-jsonnet
parser/parser.go
astVarToIdentifier
func astVarToIdentifier(node ast.Node) (*ast.Identifier, bool) { v, ok := node.(*ast.Var) if ok { return &v.Id, true } return nil, false }
go
func astVarToIdentifier(node ast.Node) (*ast.Identifier, bool) { v, ok := node.(*ast.Var) if ok { return &v.Id, true } return nil, false }
[ "func", "astVarToIdentifier", "(", "node", "ast", ".", "Node", ")", "(", "*", "ast", ".", "Identifier", ",", "bool", ")", "{", "v", ",", "ok", ":=", "node", ".", "(", "*", "ast", ".", "Var", ")", "\n", "if", "ok", "{", "return", "&", "v", ".", ...
// in some cases it's convenient to parse something as an expression, and later // decide that it should be just an identifer
[ "in", "some", "cases", "it", "s", "convenient", "to", "parse", "something", "as", "an", "expression", "and", "later", "decide", "that", "it", "should", "be", "just", "an", "identifer" ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/parser/parser.go#L125-L131
train
google/go-jsonnet
interpreter.go
popIfExists
func (s *callStack) popIfExists(whichFrame int) { if len(s.stack) == whichFrame { if s.top().isCall { s.calls-- } s.stack = s.stack[:len(s.stack)-1] } }
go
func (s *callStack) popIfExists(whichFrame int) { if len(s.stack) == whichFrame { if s.top().isCall { s.calls-- } s.stack = s.stack[:len(s.stack)-1] } }
[ "func", "(", "s", "*", "callStack", ")", "popIfExists", "(", "whichFrame", "int", ")", "{", "if", "len", "(", "s", ".", "stack", ")", "==", "whichFrame", "{", "if", "s", ".", "top", "(", ")", ".", "isCall", "{", "s", ".", "calls", "--", "\n", "...
// It might've been popped already by tail call optimization. // We check if it was trimmed by comparing the current stack size to the position // of the frame we want to pop.
[ "It", "might", "ve", "been", "popped", "already", "by", "tail", "call", "optimization", ".", "We", "check", "if", "it", "was", "trimmed", "by", "comparing", "the", "current", "stack", "size", "to", "the", "position", "of", "the", "frame", "we", "want", "...
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L119-L126
train
google/go-jsonnet
interpreter.go
tailCallTrimStack
func (s *callStack) tailCallTrimStack() { for i := len(s.stack) - 1; i >= 0; i-- { if s.stack[i].isCall { if !s.stack[i].trimmable { return } // Remove this stack frame and everything above it s.stack = s.stack[:i] s.calls-- return } } }
go
func (s *callStack) tailCallTrimStack() { for i := len(s.stack) - 1; i >= 0; i-- { if s.stack[i].isCall { if !s.stack[i].trimmable { return } // Remove this stack frame and everything above it s.stack = s.stack[:i] s.calls-- return } } }
[ "func", "(", "s", "*", "callStack", ")", "tailCallTrimStack", "(", ")", "{", "for", "i", ":=", "len", "(", "s", ".", "stack", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "s", ".", "stack", "[", "i", "]", ".", "isCall", "{...
/** If there is a trimmable frame followed by some locals, pop them all. */
[ "If", "there", "is", "a", "trimmable", "frame", "followed", "by", "some", "locals", "pop", "them", "all", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L129-L141
train
google/go-jsonnet
interpreter.go
getSelfBinding
func (s *callStack) getSelfBinding() selfBinding { for i := len(s.stack) - 1; i >= 0; i-- { if s.stack[i].isCall { return s.stack[i].env.selfBinding } } panic(fmt.Sprintf("malformed stack %v", dumpCallStack(s))) }
go
func (s *callStack) getSelfBinding() selfBinding { for i := len(s.stack) - 1; i >= 0; i-- { if s.stack[i].isCall { return s.stack[i].env.selfBinding } } panic(fmt.Sprintf("malformed stack %v", dumpCallStack(s))) }
[ "func", "(", "s", "*", "callStack", ")", "getSelfBinding", "(", ")", "selfBinding", "{", "for", "i", ":=", "len", "(", "s", ".", "stack", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "s", ".", "stack", "[", "i", "]", ".", ...
// getSelfBinding resolves the self construct
[ "getSelfBinding", "resolves", "the", "self", "construct" ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L167-L174
train
google/go-jsonnet
interpreter.go
lookUpVar
func (s *callStack) lookUpVar(id ast.Identifier) *cachedThunk { for i := len(s.stack) - 1; i >= 0; i-- { bind, present := s.stack[i].env.upValues[id] if present { return bind } if s.stack[i].isCall { // Nothing beyond the captured environment of the thunk / closure. break } } return nil }
go
func (s *callStack) lookUpVar(id ast.Identifier) *cachedThunk { for i := len(s.stack) - 1; i >= 0; i-- { bind, present := s.stack[i].env.upValues[id] if present { return bind } if s.stack[i].isCall { // Nothing beyond the captured environment of the thunk / closure. break } } return nil }
[ "func", "(", "s", "*", "callStack", ")", "lookUpVar", "(", "id", "ast", ".", "Identifier", ")", "*", "cachedThunk", "{", "for", "i", ":=", "len", "(", "s", ".", "stack", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "bind", ",", "p...
// lookUpVar finds for the closest variable in scope that matches the given name.
[ "lookUpVar", "finds", "for", "the", "closest", "variable", "in", "scope", "that", "matches", "the", "given", "name", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L177-L189
train
google/go-jsonnet
interpreter.go
capture
func (s *callStack) capture(freeVars ast.Identifiers) bindingFrame { env := make(bindingFrame) for _, fv := range freeVars { env[fv] = s.lookUpVarOrPanic(fv) } return env }
go
func (s *callStack) capture(freeVars ast.Identifiers) bindingFrame { env := make(bindingFrame) for _, fv := range freeVars { env[fv] = s.lookUpVarOrPanic(fv) } return env }
[ "func", "(", "s", "*", "callStack", ")", "capture", "(", "freeVars", "ast", ".", "Identifiers", ")", "bindingFrame", "{", "env", ":=", "make", "(", "bindingFrame", ")", "\n", "for", "_", ",", "fv", ":=", "range", "freeVars", "{", "env", "[", "fv", "]...
// Build a binding frame containing specified variables.
[ "Build", "a", "binding", "frame", "containing", "specified", "variables", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L207-L213
train
google/go-jsonnet
interpreter.go
addBindings
func addBindings(a, b bindingFrame) bindingFrame { result := make(bindingFrame) for k, v := range a { result[k] = v } for k, v := range b { result[k] = v } return result }
go
func addBindings(a, b bindingFrame) bindingFrame { result := make(bindingFrame) for k, v := range a { result[k] = v } for k, v := range b { result[k] = v } return result }
[ "func", "addBindings", "(", "a", ",", "b", "bindingFrame", ")", "bindingFrame", "{", "result", ":=", "make", "(", "bindingFrame", ")", "\n", "for", "k", ",", "v", ":=", "range", "a", "{", "result", "[", "k", "]", "=", "v", "\n", "}", "\n", "for", ...
// Map union, b takes precedence when keys collide.
[ "Map", "union", "b", "takes", "precedence", "when", "keys", "collide", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L243-L255
train
google/go-jsonnet
interpreter.go
unparseString
func unparseString(v string) string { var buf bytes.Buffer buf.WriteString("\"") for _, c := range v { switch c { case '"': buf.WriteString("\\\"") case '\\': buf.WriteString("\\\\") case '\b': buf.WriteString("\\b") case '\f': buf.WriteString("\\f") case '\n': buf.WriteString("\\n") case '\r': buf.WriteString("\\r") case '\t': buf.WriteString("\\t") case 0: buf.WriteString("\\u0000") default: if c < 0x20 || (c >= 0x7f && c <= 0x9f) { buf.WriteString(fmt.Sprintf("\\u%04x", int(c))) } else { buf.WriteRune(c) } } } buf.WriteString("\"") return buf.String() }
go
func unparseString(v string) string { var buf bytes.Buffer buf.WriteString("\"") for _, c := range v { switch c { case '"': buf.WriteString("\\\"") case '\\': buf.WriteString("\\\\") case '\b': buf.WriteString("\\b") case '\f': buf.WriteString("\\f") case '\n': buf.WriteString("\\n") case '\r': buf.WriteString("\\r") case '\t': buf.WriteString("\\t") case 0: buf.WriteString("\\u0000") default: if c < 0x20 || (c >= 0x7f && c <= 0x9f) { buf.WriteString(fmt.Sprintf("\\u%04x", int(c))) } else { buf.WriteRune(c) } } } buf.WriteString("\"") return buf.String() }
[ "func", "unparseString", "(", "v", "string", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "WriteString", "(", "\"\\\"\"", ")", "\n", "\\\"", "\n", "for", "_", ",", "c", ":=", "range", "v", "{", "switch", "c", "{", "ca...
// unparseString Wraps in "" and escapes stuff to make the string JSON-compliant and human-readable.
[ "unparseString", "Wraps", "in", "and", "escapes", "stuff", "to", "make", "the", "string", "JSON", "-", "compliant", "and", "human", "-", "readable", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L569-L600
train
google/go-jsonnet
interpreter.go
manifestString
func (i *interpreter) manifestString(buf *bytes.Buffer, trace TraceElement, v value) error { switch v := v.(type) { case *valueString: buf.WriteString(v.getString()) return nil default: return makeRuntimeError(fmt.Sprintf("expected string result, got: %s", v.getType().name), i.getCurrentStackTrace(trace)) } }
go
func (i *interpreter) manifestString(buf *bytes.Buffer, trace TraceElement, v value) error { switch v := v.(type) { case *valueString: buf.WriteString(v.getString()) return nil default: return makeRuntimeError(fmt.Sprintf("expected string result, got: %s", v.getType().name), i.getCurrentStackTrace(trace)) } }
[ "func", "(", "i", "*", "interpreter", ")", "manifestString", "(", "buf", "*", "bytes", ".", "Buffer", ",", "trace", "TraceElement", ",", "v", "value", ")", "error", "{", "switch", "v", ":=", "v", ".", "(", "type", ")", "{", "case", "*", "valueString"...
// manifestString expects the value to be a string and returns it.
[ "manifestString", "expects", "the", "value", "to", "be", "a", "string", "and", "returns", "it", "." ]
181c86d8157c7de54d052305b318be18b34d27d0
https://github.com/google/go-jsonnet/blob/181c86d8157c7de54d052305b318be18b34d27d0/interpreter.go#L790-L798
train