id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
15,100 |
limetext/backend
|
editor.go
|
GetClipboard
|
func (e *Editor) GetClipboard() string {
s, _ := e.clipboard.Get()
return s
}
|
go
|
func (e *Editor) GetClipboard() string {
s, _ := e.clipboard.Get()
return s
}
|
[
"func",
"(",
"e",
"*",
"Editor",
")",
"GetClipboard",
"(",
")",
"string",
"{",
"s",
",",
"_",
":=",
"e",
".",
"clipboard",
".",
"Get",
"(",
")",
"\n\n",
"return",
"s",
"\n",
"}"
] |
// GetClipboard returns the contents of the clipboard. It assumes the text was
// not captured from an auto-expanded cursor. It exists for Sublime Text API
// compatibility.
|
[
"GetClipboard",
"returns",
"the",
"contents",
"of",
"the",
"clipboard",
".",
"It",
"assumes",
"the",
"text",
"was",
"not",
"captured",
"from",
"an",
"auto",
"-",
"expanded",
"cursor",
".",
"It",
"exists",
"for",
"Sublime",
"Text",
"API",
"compatibility",
"."
] |
3e883f0efc3c38aa32c11c06e2e044086a4129f5
|
https://github.com/limetext/backend/blob/3e883f0efc3c38aa32c11c06e2e044086a4129f5/editor.go#L392-L396
|
15,101 |
limetext/backend
|
editor.go
|
SetClipboard
|
func (e *Editor) SetClipboard(s string) {
e.clipboard.Set(s, false)
}
|
go
|
func (e *Editor) SetClipboard(s string) {
e.clipboard.Set(s, false)
}
|
[
"func",
"(",
"e",
"*",
"Editor",
")",
"SetClipboard",
"(",
"s",
"string",
")",
"{",
"e",
".",
"clipboard",
".",
"Set",
"(",
"s",
",",
"false",
")",
"\n",
"}"
] |
// SetClipboard modifies the contents of the clipboard. It assumes the text was
// not captured from an auto-expanded cursor. It exists for Sublime Text API
// compatibility.
|
[
"SetClipboard",
"modifies",
"the",
"contents",
"of",
"the",
"clipboard",
".",
"It",
"assumes",
"the",
"text",
"was",
"not",
"captured",
"from",
"an",
"auto",
"-",
"expanded",
"cursor",
".",
"It",
"exists",
"for",
"Sublime",
"Text",
"API",
"compatibility",
"."
] |
3e883f0efc3c38aa32c11c06e2e044086a4129f5
|
https://github.com/limetext/backend/blob/3e883f0efc3c38aa32c11c06e2e044086a4129f5/editor.go#L401-L403
|
15,102 |
manyminds/api2go
|
api_public.go
|
UseMiddleware
|
func (api *API) UseMiddleware(middleware ...HandlerFunc) {
api.middlewares = append(api.middlewares, middleware...)
}
|
go
|
func (api *API) UseMiddleware(middleware ...HandlerFunc) {
api.middlewares = append(api.middlewares, middleware...)
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"UseMiddleware",
"(",
"middleware",
"...",
"HandlerFunc",
")",
"{",
"api",
".",
"middlewares",
"=",
"append",
"(",
"api",
".",
"middlewares",
",",
"middleware",
"...",
")",
"\n",
"}"
] |
// UseMiddleware registers middlewares that implement the api2go.HandlerFunc
// Middleware is run before any generated routes.
|
[
"UseMiddleware",
"registers",
"middlewares",
"that",
"implement",
"the",
"api2go",
".",
"HandlerFunc",
"Middleware",
"is",
"run",
"before",
"any",
"generated",
"routes",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api_public.go#L51-L53
|
15,103 |
manyminds/api2go
|
api_public.go
|
NewAPIVersion
|
func (api *API) NewAPIVersion(prefix string) *API {
return newAPI(prefix, api.info.resolver, api.router)
}
|
go
|
func (api *API) NewAPIVersion(prefix string) *API {
return newAPI(prefix, api.info.resolver, api.router)
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"NewAPIVersion",
"(",
"prefix",
"string",
")",
"*",
"API",
"{",
"return",
"newAPI",
"(",
"prefix",
",",
"api",
".",
"info",
".",
"resolver",
",",
"api",
".",
"router",
")",
"\n",
"}"
] |
// NewAPIVersion can be used to chain an additional API version to the routing of a previous
// one. Use this if you have multiple version prefixes and want to combine all
// your different API versions. This reuses the baseURL or URLResolver
|
[
"NewAPIVersion",
"can",
"be",
"used",
"to",
"chain",
"an",
"additional",
"API",
"version",
"to",
"the",
"routing",
"of",
"a",
"previous",
"one",
".",
"Use",
"this",
"if",
"you",
"have",
"multiple",
"version",
"prefixes",
"and",
"want",
"to",
"combine",
"all",
"your",
"different",
"API",
"versions",
".",
"This",
"reuses",
"the",
"baseURL",
"or",
"URLResolver"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api_public.go#L58-L60
|
15,104 |
manyminds/api2go
|
api_public.go
|
NewAPIWithResolver
|
func NewAPIWithResolver(prefix string, resolver URLResolver) *API {
handler := notAllowedHandler{}
r := routing.NewHTTPRouter(prefix, &handler)
api := newAPI(prefix, resolver, r)
handler.API = api
return api
}
|
go
|
func NewAPIWithResolver(prefix string, resolver URLResolver) *API {
handler := notAllowedHandler{}
r := routing.NewHTTPRouter(prefix, &handler)
api := newAPI(prefix, resolver, r)
handler.API = api
return api
}
|
[
"func",
"NewAPIWithResolver",
"(",
"prefix",
"string",
",",
"resolver",
"URLResolver",
")",
"*",
"API",
"{",
"handler",
":=",
"notAllowedHandler",
"{",
"}",
"\n",
"r",
":=",
"routing",
".",
"NewHTTPRouter",
"(",
"prefix",
",",
"&",
"handler",
")",
"\n",
"api",
":=",
"newAPI",
"(",
"prefix",
",",
"resolver",
",",
"r",
")",
"\n",
"handler",
".",
"API",
"=",
"api",
"\n",
"return",
"api",
"\n",
"}"
] |
// NewAPIWithResolver can be used to create an API with a custom URL resolver.
|
[
"NewAPIWithResolver",
"can",
"be",
"used",
"to",
"create",
"an",
"API",
"with",
"a",
"custom",
"URL",
"resolver",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api_public.go#L63-L69
|
15,105 |
manyminds/api2go
|
api_public.go
|
NewAPI
|
func NewAPI(prefix string) *API {
handler := notAllowedHandler{}
staticResolver := NewStaticResolver("")
r := routing.NewHTTPRouter(prefix, &handler)
api := newAPI(prefix, staticResolver, r)
handler.API = api
return api
}
|
go
|
func NewAPI(prefix string) *API {
handler := notAllowedHandler{}
staticResolver := NewStaticResolver("")
r := routing.NewHTTPRouter(prefix, &handler)
api := newAPI(prefix, staticResolver, r)
handler.API = api
return api
}
|
[
"func",
"NewAPI",
"(",
"prefix",
"string",
")",
"*",
"API",
"{",
"handler",
":=",
"notAllowedHandler",
"{",
"}",
"\n",
"staticResolver",
":=",
"NewStaticResolver",
"(",
"\"",
"\"",
")",
"\n",
"r",
":=",
"routing",
".",
"NewHTTPRouter",
"(",
"prefix",
",",
"&",
"handler",
")",
"\n",
"api",
":=",
"newAPI",
"(",
"prefix",
",",
"staticResolver",
",",
"r",
")",
"\n",
"handler",
".",
"API",
"=",
"api",
"\n",
"return",
"api",
"\n",
"}"
] |
// NewAPI returns an initialized API instance
// `prefix` is added in front of all endpoints.
|
[
"NewAPI",
"returns",
"an",
"initialized",
"API",
"instance",
"prefix",
"is",
"added",
"in",
"front",
"of",
"all",
"endpoints",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api_public.go#L85-L92
|
15,106 |
manyminds/api2go
|
api_public.go
|
newAPI
|
func newAPI(prefix string, resolver URLResolver, router routing.Routeable) *API {
// Add initial and trailing slash to prefix
prefixSlashes := strings.Trim(prefix, "/")
if len(prefixSlashes) > 0 {
prefixSlashes = "/" + prefixSlashes + "/"
} else {
prefixSlashes = "/"
}
info := information{prefix: prefix, resolver: resolver}
api := &API{
ContentType: defaultContentTypHeader,
router: router,
info: info,
middlewares: make([]HandlerFunc, 0),
contextAllocator: nil,
}
api.contextPool.New = func() interface{} {
if api.contextAllocator != nil {
return api.contextAllocator(api)
}
return api.allocateDefaultContext()
}
return api
}
|
go
|
func newAPI(prefix string, resolver URLResolver, router routing.Routeable) *API {
// Add initial and trailing slash to prefix
prefixSlashes := strings.Trim(prefix, "/")
if len(prefixSlashes) > 0 {
prefixSlashes = "/" + prefixSlashes + "/"
} else {
prefixSlashes = "/"
}
info := information{prefix: prefix, resolver: resolver}
api := &API{
ContentType: defaultContentTypHeader,
router: router,
info: info,
middlewares: make([]HandlerFunc, 0),
contextAllocator: nil,
}
api.contextPool.New = func() interface{} {
if api.contextAllocator != nil {
return api.contextAllocator(api)
}
return api.allocateDefaultContext()
}
return api
}
|
[
"func",
"newAPI",
"(",
"prefix",
"string",
",",
"resolver",
"URLResolver",
",",
"router",
"routing",
".",
"Routeable",
")",
"*",
"API",
"{",
"// Add initial and trailing slash to prefix",
"prefixSlashes",
":=",
"strings",
".",
"Trim",
"(",
"prefix",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"prefixSlashes",
")",
">",
"0",
"{",
"prefixSlashes",
"=",
"\"",
"\"",
"+",
"prefixSlashes",
"+",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"prefixSlashes",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"info",
":=",
"information",
"{",
"prefix",
":",
"prefix",
",",
"resolver",
":",
"resolver",
"}",
"\n\n",
"api",
":=",
"&",
"API",
"{",
"ContentType",
":",
"defaultContentTypHeader",
",",
"router",
":",
"router",
",",
"info",
":",
"info",
",",
"middlewares",
":",
"make",
"(",
"[",
"]",
"HandlerFunc",
",",
"0",
")",
",",
"contextAllocator",
":",
"nil",
",",
"}",
"\n\n",
"api",
".",
"contextPool",
".",
"New",
"=",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"if",
"api",
".",
"contextAllocator",
"!=",
"nil",
"{",
"return",
"api",
".",
"contextAllocator",
"(",
"api",
")",
"\n",
"}",
"\n",
"return",
"api",
".",
"allocateDefaultContext",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"api",
"\n",
"}"
] |
// newAPI is now an internal method that can be changed if params are changing
|
[
"newAPI",
"is",
"now",
"an",
"internal",
"method",
"that",
"can",
"be",
"changed",
"if",
"params",
"are",
"changing"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api_public.go#L107-L134
|
15,107 |
manyminds/api2go
|
api.go
|
middlewareChain
|
func (api *API) middlewareChain(c APIContexter, w http.ResponseWriter, r *http.Request) {
for _, middleware := range api.middlewares {
middleware(c, w, r)
}
}
|
go
|
func (api *API) middlewareChain(c APIContexter, w http.ResponseWriter, r *http.Request) {
for _, middleware := range api.middlewares {
middleware(c, w, r)
}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"middlewareChain",
"(",
"c",
"APIContexter",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"for",
"_",
",",
"middleware",
":=",
"range",
"api",
".",
"middlewares",
"{",
"middleware",
"(",
"c",
",",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// middlewareChain executes the middleeware chain setup
|
[
"middlewareChain",
"executes",
"the",
"middleeware",
"chain",
"setup"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api.go#L192-L196
|
15,108 |
manyminds/api2go
|
api.go
|
handleLinked
|
func (res *resource) handleLinked(c APIContexter, api *API, w http.ResponseWriter, r *http.Request, params map[string]string, linked jsonapi.Reference, info information) error {
id := params["id"]
for _, resource := range api.resources {
if resource.name == linked.Type {
request := buildRequest(c, r)
request.QueryParams[res.name+"ID"] = []string{id}
request.QueryParams[res.name+"Name"] = []string{linked.Name}
if source, ok := resource.source.(PaginatedFindAll); ok {
// check for pagination, otherwise normal FindAll
pagination := newPaginationQueryParams(r)
if pagination.isValid() {
var count uint
count, response, err := source.PaginatedFindAll(request)
if err != nil {
return err
}
paginationLinks, err := pagination.getLinks(r, count, info)
if err != nil {
return err
}
return res.respondWithPagination(response, info, http.StatusOK, paginationLinks, w, r)
}
}
source, ok := resource.source.(FindAll)
if !ok {
return NewHTTPError(nil, "Resource does not implement the FindAll interface", http.StatusNotFound)
}
obj, err := source.FindAll(request)
if err != nil {
return err
}
return res.respondWith(obj, info, http.StatusOK, w, r)
}
}
return NewHTTPError(
errors.New("Not Found"),
"No resource handler is registered to handle the linked resource "+linked.Name,
http.StatusNotFound,
)
}
|
go
|
func (res *resource) handleLinked(c APIContexter, api *API, w http.ResponseWriter, r *http.Request, params map[string]string, linked jsonapi.Reference, info information) error {
id := params["id"]
for _, resource := range api.resources {
if resource.name == linked.Type {
request := buildRequest(c, r)
request.QueryParams[res.name+"ID"] = []string{id}
request.QueryParams[res.name+"Name"] = []string{linked.Name}
if source, ok := resource.source.(PaginatedFindAll); ok {
// check for pagination, otherwise normal FindAll
pagination := newPaginationQueryParams(r)
if pagination.isValid() {
var count uint
count, response, err := source.PaginatedFindAll(request)
if err != nil {
return err
}
paginationLinks, err := pagination.getLinks(r, count, info)
if err != nil {
return err
}
return res.respondWithPagination(response, info, http.StatusOK, paginationLinks, w, r)
}
}
source, ok := resource.source.(FindAll)
if !ok {
return NewHTTPError(nil, "Resource does not implement the FindAll interface", http.StatusNotFound)
}
obj, err := source.FindAll(request)
if err != nil {
return err
}
return res.respondWith(obj, info, http.StatusOK, w, r)
}
}
return NewHTTPError(
errors.New("Not Found"),
"No resource handler is registered to handle the linked resource "+linked.Name,
http.StatusNotFound,
)
}
|
[
"func",
"(",
"res",
"*",
"resource",
")",
"handleLinked",
"(",
"c",
"APIContexter",
",",
"api",
"*",
"API",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
",",
"linked",
"jsonapi",
".",
"Reference",
",",
"info",
"information",
")",
"error",
"{",
"id",
":=",
"params",
"[",
"\"",
"\"",
"]",
"\n",
"for",
"_",
",",
"resource",
":=",
"range",
"api",
".",
"resources",
"{",
"if",
"resource",
".",
"name",
"==",
"linked",
".",
"Type",
"{",
"request",
":=",
"buildRequest",
"(",
"c",
",",
"r",
")",
"\n",
"request",
".",
"QueryParams",
"[",
"res",
".",
"name",
"+",
"\"",
"\"",
"]",
"=",
"[",
"]",
"string",
"{",
"id",
"}",
"\n",
"request",
".",
"QueryParams",
"[",
"res",
".",
"name",
"+",
"\"",
"\"",
"]",
"=",
"[",
"]",
"string",
"{",
"linked",
".",
"Name",
"}",
"\n\n",
"if",
"source",
",",
"ok",
":=",
"resource",
".",
"source",
".",
"(",
"PaginatedFindAll",
")",
";",
"ok",
"{",
"// check for pagination, otherwise normal FindAll",
"pagination",
":=",
"newPaginationQueryParams",
"(",
"r",
")",
"\n",
"if",
"pagination",
".",
"isValid",
"(",
")",
"{",
"var",
"count",
"uint",
"\n",
"count",
",",
"response",
",",
"err",
":=",
"source",
".",
"PaginatedFindAll",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"paginationLinks",
",",
"err",
":=",
"pagination",
".",
"getLinks",
"(",
"r",
",",
"count",
",",
"info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"res",
".",
"respondWithPagination",
"(",
"response",
",",
"info",
",",
"http",
".",
"StatusOK",
",",
"paginationLinks",
",",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"source",
",",
"ok",
":=",
"resource",
".",
"source",
".",
"(",
"FindAll",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewHTTPError",
"(",
"nil",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"\n\n",
"obj",
",",
"err",
":=",
"source",
".",
"FindAll",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"res",
".",
"respondWith",
"(",
"obj",
",",
"info",
",",
"http",
".",
"StatusOK",
",",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"NewHTTPError",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
"+",
"linked",
".",
"Name",
",",
"http",
".",
"StatusNotFound",
",",
")",
"\n",
"}"
] |
// try to find the referenced resource and call the findAll Method with referencing resource id as param
|
[
"try",
"to",
"find",
"the",
"referenced",
"resource",
"and",
"call",
"the",
"findAll",
"Method",
"with",
"referencing",
"resource",
"id",
"as",
"param"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/api.go#L617-L662
|
15,109 |
manyminds/api2go
|
response.go
|
Links
|
func (r Response) Links(req *http.Request, baseURL string) (ret jsonapi.Links) {
ret = make(jsonapi.Links)
if r.Pagination.Next != nil {
ret["next"] = buildLink(baseURL, req, r.Pagination.Next)
}
if r.Pagination.Prev != nil {
ret["prev"] = buildLink(baseURL, req, r.Pagination.Prev)
}
if r.Pagination.First != nil {
ret["first"] = buildLink(baseURL, req, r.Pagination.First)
}
if r.Pagination.Last != nil {
ret["last"] = buildLink(baseURL, req, r.Pagination.Last)
}
return
}
|
go
|
func (r Response) Links(req *http.Request, baseURL string) (ret jsonapi.Links) {
ret = make(jsonapi.Links)
if r.Pagination.Next != nil {
ret["next"] = buildLink(baseURL, req, r.Pagination.Next)
}
if r.Pagination.Prev != nil {
ret["prev"] = buildLink(baseURL, req, r.Pagination.Prev)
}
if r.Pagination.First != nil {
ret["first"] = buildLink(baseURL, req, r.Pagination.First)
}
if r.Pagination.Last != nil {
ret["last"] = buildLink(baseURL, req, r.Pagination.Last)
}
return
}
|
[
"func",
"(",
"r",
"Response",
")",
"Links",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"baseURL",
"string",
")",
"(",
"ret",
"jsonapi",
".",
"Links",
")",
"{",
"ret",
"=",
"make",
"(",
"jsonapi",
".",
"Links",
")",
"\n\n",
"if",
"r",
".",
"Pagination",
".",
"Next",
"!=",
"nil",
"{",
"ret",
"[",
"\"",
"\"",
"]",
"=",
"buildLink",
"(",
"baseURL",
",",
"req",
",",
"r",
".",
"Pagination",
".",
"Next",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Pagination",
".",
"Prev",
"!=",
"nil",
"{",
"ret",
"[",
"\"",
"\"",
"]",
"=",
"buildLink",
"(",
"baseURL",
",",
"req",
",",
"r",
".",
"Pagination",
".",
"Prev",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Pagination",
".",
"First",
"!=",
"nil",
"{",
"ret",
"[",
"\"",
"\"",
"]",
"=",
"buildLink",
"(",
"baseURL",
",",
"req",
",",
"r",
".",
"Pagination",
".",
"First",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Pagination",
".",
"Last",
"!=",
"nil",
"{",
"ret",
"[",
"\"",
"\"",
"]",
"=",
"buildLink",
"(",
"baseURL",
",",
"req",
",",
"r",
".",
"Pagination",
".",
"Last",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Links returns a jsonapi.Links object to include in the top-level response
|
[
"Links",
"returns",
"a",
"jsonapi",
".",
"Links",
"object",
"to",
"include",
"in",
"the",
"top",
"-",
"level",
"response"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/response.go#L51-L67
|
15,110 |
manyminds/api2go
|
examples/storage/storage_user.go
|
Insert
|
func (s *UserStorage) Insert(c model.User) string {
id := fmt.Sprintf("%d", s.idCount)
c.ID = id
s.users[id] = &c
s.idCount++
return id
}
|
go
|
func (s *UserStorage) Insert(c model.User) string {
id := fmt.Sprintf("%d", s.idCount)
c.ID = id
s.users[id] = &c
s.idCount++
return id
}
|
[
"func",
"(",
"s",
"*",
"UserStorage",
")",
"Insert",
"(",
"c",
"model",
".",
"User",
")",
"string",
"{",
"id",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
".",
"idCount",
")",
"\n",
"c",
".",
"ID",
"=",
"id",
"\n",
"s",
".",
"users",
"[",
"id",
"]",
"=",
"&",
"c",
"\n",
"s",
".",
"idCount",
"++",
"\n",
"return",
"id",
"\n",
"}"
] |
// Insert a user
|
[
"Insert",
"a",
"user"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/storage/storage_user.go#L39-L45
|
15,111 |
manyminds/api2go
|
examples/resolver/resolver.go
|
GetBaseURL
|
func (m RequestURL) GetBaseURL() string {
if uri := m.r.Header.Get("REQUEST_URI"); uri != "" {
return uri
}
return fmt.Sprintf("https://localhost:%d", m.Port)
}
|
go
|
func (m RequestURL) GetBaseURL() string {
if uri := m.r.Header.Get("REQUEST_URI"); uri != "" {
return uri
}
return fmt.Sprintf("https://localhost:%d", m.Port)
}
|
[
"func",
"(",
"m",
"RequestURL",
")",
"GetBaseURL",
"(",
")",
"string",
"{",
"if",
"uri",
":=",
"m",
".",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"uri",
"!=",
"\"",
"\"",
"{",
"return",
"uri",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
".",
"Port",
")",
"\n",
"}"
] |
//GetBaseURL implements `URLResolver` interface
|
[
"GetBaseURL",
"implements",
"URLResolver",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resolver/resolver.go#L22-L28
|
15,112 |
manyminds/api2go
|
examples/resource/resource_user.go
|
FindAll
|
func (s UserResource) FindAll(r api2go.Request) (api2go.Responder, error) {
var result []model.User
users := s.UserStorage.GetAll()
for _, user := range users {
// get all sweets for the user
user.Chocolates = []*model.Chocolate{}
for _, chocolateID := range user.ChocolatesIDs {
choc, err := s.ChocStorage.GetOne(chocolateID)
if err != nil {
return &Response{}, err
}
user.Chocolates = append(user.Chocolates, &choc)
}
result = append(result, *user)
}
return &Response{Res: result}, nil
}
|
go
|
func (s UserResource) FindAll(r api2go.Request) (api2go.Responder, error) {
var result []model.User
users := s.UserStorage.GetAll()
for _, user := range users {
// get all sweets for the user
user.Chocolates = []*model.Chocolate{}
for _, chocolateID := range user.ChocolatesIDs {
choc, err := s.ChocStorage.GetOne(chocolateID)
if err != nil {
return &Response{}, err
}
user.Chocolates = append(user.Chocolates, &choc)
}
result = append(result, *user)
}
return &Response{Res: result}, nil
}
|
[
"func",
"(",
"s",
"UserResource",
")",
"FindAll",
"(",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"var",
"result",
"[",
"]",
"model",
".",
"User",
"\n",
"users",
":=",
"s",
".",
"UserStorage",
".",
"GetAll",
"(",
")",
"\n\n",
"for",
"_",
",",
"user",
":=",
"range",
"users",
"{",
"// get all sweets for the user",
"user",
".",
"Chocolates",
"=",
"[",
"]",
"*",
"model",
".",
"Chocolate",
"{",
"}",
"\n",
"for",
"_",
",",
"chocolateID",
":=",
"range",
"user",
".",
"ChocolatesIDs",
"{",
"choc",
",",
"err",
":=",
"s",
".",
"ChocStorage",
".",
"GetOne",
"(",
"chocolateID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"user",
".",
"Chocolates",
"=",
"append",
"(",
"user",
".",
"Chocolates",
",",
"&",
"choc",
")",
"\n",
"}",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"*",
"user",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Response",
"{",
"Res",
":",
"result",
"}",
",",
"nil",
"\n",
"}"
] |
// FindAll to satisfy api2go data source interface
|
[
"FindAll",
"to",
"satisfy",
"api2go",
"data",
"source",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_user.go#L21-L39
|
15,113 |
manyminds/api2go
|
examples/resource/resource_user.go
|
PaginatedFindAll
|
func (s UserResource) PaginatedFindAll(r api2go.Request) (uint, api2go.Responder, error) {
var (
result []model.User
number, size, offset, limit string
keys []int
)
users := s.UserStorage.GetAll()
for k := range users {
i, err := strconv.ParseInt(k, 10, 64)
if err != nil {
return 0, &Response{}, err
}
keys = append(keys, int(i))
}
sort.Ints(keys)
numberQuery, ok := r.QueryParams["page[number]"]
if ok {
number = numberQuery[0]
}
sizeQuery, ok := r.QueryParams["page[size]"]
if ok {
size = sizeQuery[0]
}
offsetQuery, ok := r.QueryParams["page[offset]"]
if ok {
offset = offsetQuery[0]
}
limitQuery, ok := r.QueryParams["page[limit]"]
if ok {
limit = limitQuery[0]
}
if size != "" {
sizeI, err := strconv.ParseUint(size, 10, 64)
if err != nil {
return 0, &Response{}, err
}
numberI, err := strconv.ParseUint(number, 10, 64)
if err != nil {
return 0, &Response{}, err
}
start := sizeI * (numberI - 1)
for i := start; i < start+sizeI; i++ {
if i >= uint64(len(users)) {
break
}
result = append(result, *users[strconv.FormatInt(int64(keys[i]), 10)])
}
} else {
limitI, err := strconv.ParseUint(limit, 10, 64)
if err != nil {
return 0, &Response{}, err
}
offsetI, err := strconv.ParseUint(offset, 10, 64)
if err != nil {
return 0, &Response{}, err
}
for i := offsetI; i < offsetI+limitI; i++ {
if i >= uint64(len(users)) {
break
}
result = append(result, *users[strconv.FormatInt(int64(keys[i]), 10)])
}
}
return uint(len(users)), &Response{Res: result}, nil
}
|
go
|
func (s UserResource) PaginatedFindAll(r api2go.Request) (uint, api2go.Responder, error) {
var (
result []model.User
number, size, offset, limit string
keys []int
)
users := s.UserStorage.GetAll()
for k := range users {
i, err := strconv.ParseInt(k, 10, 64)
if err != nil {
return 0, &Response{}, err
}
keys = append(keys, int(i))
}
sort.Ints(keys)
numberQuery, ok := r.QueryParams["page[number]"]
if ok {
number = numberQuery[0]
}
sizeQuery, ok := r.QueryParams["page[size]"]
if ok {
size = sizeQuery[0]
}
offsetQuery, ok := r.QueryParams["page[offset]"]
if ok {
offset = offsetQuery[0]
}
limitQuery, ok := r.QueryParams["page[limit]"]
if ok {
limit = limitQuery[0]
}
if size != "" {
sizeI, err := strconv.ParseUint(size, 10, 64)
if err != nil {
return 0, &Response{}, err
}
numberI, err := strconv.ParseUint(number, 10, 64)
if err != nil {
return 0, &Response{}, err
}
start := sizeI * (numberI - 1)
for i := start; i < start+sizeI; i++ {
if i >= uint64(len(users)) {
break
}
result = append(result, *users[strconv.FormatInt(int64(keys[i]), 10)])
}
} else {
limitI, err := strconv.ParseUint(limit, 10, 64)
if err != nil {
return 0, &Response{}, err
}
offsetI, err := strconv.ParseUint(offset, 10, 64)
if err != nil {
return 0, &Response{}, err
}
for i := offsetI; i < offsetI+limitI; i++ {
if i >= uint64(len(users)) {
break
}
result = append(result, *users[strconv.FormatInt(int64(keys[i]), 10)])
}
}
return uint(len(users)), &Response{Res: result}, nil
}
|
[
"func",
"(",
"s",
"UserResource",
")",
"PaginatedFindAll",
"(",
"r",
"api2go",
".",
"Request",
")",
"(",
"uint",
",",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"var",
"(",
"result",
"[",
"]",
"model",
".",
"User",
"\n",
"number",
",",
"size",
",",
"offset",
",",
"limit",
"string",
"\n",
"keys",
"[",
"]",
"int",
"\n",
")",
"\n",
"users",
":=",
"s",
".",
"UserStorage",
".",
"GetAll",
"(",
")",
"\n\n",
"for",
"k",
":=",
"range",
"users",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"k",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"keys",
"=",
"append",
"(",
"keys",
",",
"int",
"(",
"i",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Ints",
"(",
"keys",
")",
"\n\n",
"numberQuery",
",",
"ok",
":=",
"r",
".",
"QueryParams",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"number",
"=",
"numberQuery",
"[",
"0",
"]",
"\n",
"}",
"\n",
"sizeQuery",
",",
"ok",
":=",
"r",
".",
"QueryParams",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"size",
"=",
"sizeQuery",
"[",
"0",
"]",
"\n",
"}",
"\n",
"offsetQuery",
",",
"ok",
":=",
"r",
".",
"QueryParams",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"offset",
"=",
"offsetQuery",
"[",
"0",
"]",
"\n",
"}",
"\n",
"limitQuery",
",",
"ok",
":=",
"r",
".",
"QueryParams",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"limit",
"=",
"limitQuery",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"if",
"size",
"!=",
"\"",
"\"",
"{",
"sizeI",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"size",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"numberI",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"number",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"start",
":=",
"sizeI",
"*",
"(",
"numberI",
"-",
"1",
")",
"\n",
"for",
"i",
":=",
"start",
";",
"i",
"<",
"start",
"+",
"sizeI",
";",
"i",
"++",
"{",
"if",
"i",
">=",
"uint64",
"(",
"len",
"(",
"users",
")",
")",
"{",
"break",
"\n",
"}",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"*",
"users",
"[",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"keys",
"[",
"i",
"]",
")",
",",
"10",
")",
"]",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"limitI",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"limit",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"offsetI",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"offset",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"offsetI",
";",
"i",
"<",
"offsetI",
"+",
"limitI",
";",
"i",
"++",
"{",
"if",
"i",
">=",
"uint64",
"(",
"len",
"(",
"users",
")",
")",
"{",
"break",
"\n",
"}",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"*",
"users",
"[",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"keys",
"[",
"i",
"]",
")",
",",
"10",
")",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"uint",
"(",
"len",
"(",
"users",
")",
")",
",",
"&",
"Response",
"{",
"Res",
":",
"result",
"}",
",",
"nil",
"\n",
"}"
] |
// PaginatedFindAll can be used to load users in chunks
|
[
"PaginatedFindAll",
"can",
"be",
"used",
"to",
"load",
"users",
"in",
"chunks"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_user.go#L42-L115
|
15,114 |
manyminds/api2go
|
examples/resource/resource_user.go
|
FindOne
|
func (s UserResource) FindOne(ID string, r api2go.Request) (api2go.Responder, error) {
user, err := s.UserStorage.GetOne(ID)
if err != nil {
return &Response{}, api2go.NewHTTPError(err, err.Error(), http.StatusNotFound)
}
user.Chocolates = []*model.Chocolate{}
for _, chocolateID := range user.ChocolatesIDs {
choc, err := s.ChocStorage.GetOne(chocolateID)
if err != nil {
return &Response{}, err
}
user.Chocolates = append(user.Chocolates, &choc)
}
return &Response{Res: user}, nil
}
|
go
|
func (s UserResource) FindOne(ID string, r api2go.Request) (api2go.Responder, error) {
user, err := s.UserStorage.GetOne(ID)
if err != nil {
return &Response{}, api2go.NewHTTPError(err, err.Error(), http.StatusNotFound)
}
user.Chocolates = []*model.Chocolate{}
for _, chocolateID := range user.ChocolatesIDs {
choc, err := s.ChocStorage.GetOne(chocolateID)
if err != nil {
return &Response{}, err
}
user.Chocolates = append(user.Chocolates, &choc)
}
return &Response{Res: user}, nil
}
|
[
"func",
"(",
"s",
"UserResource",
")",
"FindOne",
"(",
"ID",
"string",
",",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"user",
",",
"err",
":=",
"s",
".",
"UserStorage",
".",
"GetOne",
"(",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"api2go",
".",
"NewHTTPError",
"(",
"err",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"\n\n",
"user",
".",
"Chocolates",
"=",
"[",
"]",
"*",
"model",
".",
"Chocolate",
"{",
"}",
"\n",
"for",
"_",
",",
"chocolateID",
":=",
"range",
"user",
".",
"ChocolatesIDs",
"{",
"choc",
",",
"err",
":=",
"s",
".",
"ChocStorage",
".",
"GetOne",
"(",
"chocolateID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"user",
".",
"Chocolates",
"=",
"append",
"(",
"user",
".",
"Chocolates",
",",
"&",
"choc",
")",
"\n",
"}",
"\n",
"return",
"&",
"Response",
"{",
"Res",
":",
"user",
"}",
",",
"nil",
"\n",
"}"
] |
// FindOne to satisfy `api2go.DataSource` interface
// this method should return the user with the given ID, otherwise an error
|
[
"FindOne",
"to",
"satisfy",
"api2go",
".",
"DataSource",
"interface",
"this",
"method",
"should",
"return",
"the",
"user",
"with",
"the",
"given",
"ID",
"otherwise",
"an",
"error"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_user.go#L119-L134
|
15,115 |
manyminds/api2go
|
examples/resource/resource_user.go
|
Create
|
func (s UserResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
user, ok := obj.(model.User)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id := s.UserStorage.Insert(user)
user.ID = id
return &Response{Res: user, Code: http.StatusCreated}, nil
}
|
go
|
func (s UserResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
user, ok := obj.(model.User)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id := s.UserStorage.Insert(user)
user.ID = id
return &Response{Res: user, Code: http.StatusCreated}, nil
}
|
[
"func",
"(",
"s",
"UserResource",
")",
"Create",
"(",
"obj",
"interface",
"{",
"}",
",",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"user",
",",
"ok",
":=",
"obj",
".",
"(",
"model",
".",
"User",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"api2go",
".",
"NewHTTPError",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n\n",
"id",
":=",
"s",
".",
"UserStorage",
".",
"Insert",
"(",
"user",
")",
"\n",
"user",
".",
"ID",
"=",
"id",
"\n\n",
"return",
"&",
"Response",
"{",
"Res",
":",
"user",
",",
"Code",
":",
"http",
".",
"StatusCreated",
"}",
",",
"nil",
"\n",
"}"
] |
// Create method to satisfy `api2go.DataSource` interface
|
[
"Create",
"method",
"to",
"satisfy",
"api2go",
".",
"DataSource",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_user.go#L137-L147
|
15,116 |
manyminds/api2go
|
examples/resource/resource_user.go
|
Delete
|
func (s UserResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {
err := s.UserStorage.Delete(id)
return &Response{Code: http.StatusNoContent}, err
}
|
go
|
func (s UserResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {
err := s.UserStorage.Delete(id)
return &Response{Code: http.StatusNoContent}, err
}
|
[
"func",
"(",
"s",
"UserResource",
")",
"Delete",
"(",
"id",
"string",
",",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"err",
":=",
"s",
".",
"UserStorage",
".",
"Delete",
"(",
"id",
")",
"\n",
"return",
"&",
"Response",
"{",
"Code",
":",
"http",
".",
"StatusNoContent",
"}",
",",
"err",
"\n",
"}"
] |
// Delete to satisfy `api2go.DataSource` interface
|
[
"Delete",
"to",
"satisfy",
"api2go",
".",
"DataSource",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_user.go#L150-L153
|
15,117 |
manyminds/api2go
|
examples/resource/resource_user.go
|
Update
|
func (s UserResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
user, ok := obj.(model.User)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := s.UserStorage.Update(user)
return &Response{Res: user, Code: http.StatusNoContent}, err
}
|
go
|
func (s UserResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
user, ok := obj.(model.User)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := s.UserStorage.Update(user)
return &Response{Res: user, Code: http.StatusNoContent}, err
}
|
[
"func",
"(",
"s",
"UserResource",
")",
"Update",
"(",
"obj",
"interface",
"{",
"}",
",",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"user",
",",
"ok",
":=",
"obj",
".",
"(",
"model",
".",
"User",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"api2go",
".",
"NewHTTPError",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"s",
".",
"UserStorage",
".",
"Update",
"(",
"user",
")",
"\n",
"return",
"&",
"Response",
"{",
"Res",
":",
"user",
",",
"Code",
":",
"http",
".",
"StatusNoContent",
"}",
",",
"err",
"\n",
"}"
] |
//Update stores all changes on the user
|
[
"Update",
"stores",
"all",
"changes",
"on",
"the",
"user"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_user.go#L156-L164
|
15,118 |
manyminds/api2go
|
examples/model/model_user.go
|
GetReferencedIDs
|
func (u User) GetReferencedIDs() []jsonapi.ReferenceID {
result := []jsonapi.ReferenceID{}
for _, chocolateID := range u.ChocolatesIDs {
result = append(result, jsonapi.ReferenceID{
ID: chocolateID,
Type: "chocolates",
Name: "sweets",
})
}
return result
}
|
go
|
func (u User) GetReferencedIDs() []jsonapi.ReferenceID {
result := []jsonapi.ReferenceID{}
for _, chocolateID := range u.ChocolatesIDs {
result = append(result, jsonapi.ReferenceID{
ID: chocolateID,
Type: "chocolates",
Name: "sweets",
})
}
return result
}
|
[
"func",
"(",
"u",
"User",
")",
"GetReferencedIDs",
"(",
")",
"[",
"]",
"jsonapi",
".",
"ReferenceID",
"{",
"result",
":=",
"[",
"]",
"jsonapi",
".",
"ReferenceID",
"{",
"}",
"\n",
"for",
"_",
",",
"chocolateID",
":=",
"range",
"u",
".",
"ChocolatesIDs",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"jsonapi",
".",
"ReferenceID",
"{",
"ID",
":",
"chocolateID",
",",
"Type",
":",
"\"",
"\"",
",",
"Name",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// GetReferencedIDs to satisfy the jsonapi.MarshalLinkedRelations interface
|
[
"GetReferencedIDs",
"to",
"satisfy",
"the",
"jsonapi",
".",
"MarshalLinkedRelations",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/model/model_user.go#L42-L53
|
15,119 |
manyminds/api2go
|
examples/model/model_user.go
|
GetReferencedStructs
|
func (u User) GetReferencedStructs() []jsonapi.MarshalIdentifier {
result := []jsonapi.MarshalIdentifier{}
for key := range u.Chocolates {
result = append(result, u.Chocolates[key])
}
return result
}
|
go
|
func (u User) GetReferencedStructs() []jsonapi.MarshalIdentifier {
result := []jsonapi.MarshalIdentifier{}
for key := range u.Chocolates {
result = append(result, u.Chocolates[key])
}
return result
}
|
[
"func",
"(",
"u",
"User",
")",
"GetReferencedStructs",
"(",
")",
"[",
"]",
"jsonapi",
".",
"MarshalIdentifier",
"{",
"result",
":=",
"[",
"]",
"jsonapi",
".",
"MarshalIdentifier",
"{",
"}",
"\n",
"for",
"key",
":=",
"range",
"u",
".",
"Chocolates",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"u",
".",
"Chocolates",
"[",
"key",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// GetReferencedStructs to satisfy the jsonapi.MarhsalIncludedRelations interface
|
[
"GetReferencedStructs",
"to",
"satisfy",
"the",
"jsonapi",
".",
"MarhsalIncludedRelations",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/model/model_user.go#L56-L63
|
15,120 |
manyminds/api2go
|
examples/model/model_user.go
|
SetToManyReferenceIDs
|
func (u *User) SetToManyReferenceIDs(name string, IDs []string) error {
if name == "sweets" {
u.ChocolatesIDs = IDs
return nil
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
go
|
func (u *User) SetToManyReferenceIDs(name string, IDs []string) error {
if name == "sweets" {
u.ChocolatesIDs = IDs
return nil
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
[
"func",
"(",
"u",
"*",
"User",
")",
"SetToManyReferenceIDs",
"(",
"name",
"string",
",",
"IDs",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"u",
".",
"ChocolatesIDs",
"=",
"IDs",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}"
] |
// SetToManyReferenceIDs sets the sweets reference IDs and satisfies the jsonapi.UnmarshalToManyRelations interface
|
[
"SetToManyReferenceIDs",
"sets",
"the",
"sweets",
"reference",
"IDs",
"and",
"satisfies",
"the",
"jsonapi",
".",
"UnmarshalToManyRelations",
"interface"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/model/model_user.go#L66-L73
|
15,121 |
manyminds/api2go
|
examples/model/model_user.go
|
AddToManyIDs
|
func (u *User) AddToManyIDs(name string, IDs []string) error {
if name == "sweets" {
u.ChocolatesIDs = append(u.ChocolatesIDs, IDs...)
return nil
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
go
|
func (u *User) AddToManyIDs(name string, IDs []string) error {
if name == "sweets" {
u.ChocolatesIDs = append(u.ChocolatesIDs, IDs...)
return nil
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
[
"func",
"(",
"u",
"*",
"User",
")",
"AddToManyIDs",
"(",
"name",
"string",
",",
"IDs",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"u",
".",
"ChocolatesIDs",
"=",
"append",
"(",
"u",
".",
"ChocolatesIDs",
",",
"IDs",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}"
] |
// AddToManyIDs adds some new sweets that a users loves so much
|
[
"AddToManyIDs",
"adds",
"some",
"new",
"sweets",
"that",
"a",
"users",
"loves",
"so",
"much"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/model/model_user.go#L76-L83
|
15,122 |
manyminds/api2go
|
examples/model/model_user.go
|
DeleteToManyIDs
|
func (u *User) DeleteToManyIDs(name string, IDs []string) error {
if name == "sweets" {
for _, ID := range IDs {
for pos, oldID := range u.ChocolatesIDs {
if ID == oldID {
// match, this ID must be removed
u.ChocolatesIDs = append(u.ChocolatesIDs[:pos], u.ChocolatesIDs[pos+1:]...)
}
}
}
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
go
|
func (u *User) DeleteToManyIDs(name string, IDs []string) error {
if name == "sweets" {
for _, ID := range IDs {
for pos, oldID := range u.ChocolatesIDs {
if ID == oldID {
// match, this ID must be removed
u.ChocolatesIDs = append(u.ChocolatesIDs[:pos], u.ChocolatesIDs[pos+1:]...)
}
}
}
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
[
"func",
"(",
"u",
"*",
"User",
")",
"DeleteToManyIDs",
"(",
"name",
"string",
",",
"IDs",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"for",
"_",
",",
"ID",
":=",
"range",
"IDs",
"{",
"for",
"pos",
",",
"oldID",
":=",
"range",
"u",
".",
"ChocolatesIDs",
"{",
"if",
"ID",
"==",
"oldID",
"{",
"// match, this ID must be removed",
"u",
".",
"ChocolatesIDs",
"=",
"append",
"(",
"u",
".",
"ChocolatesIDs",
"[",
":",
"pos",
"]",
",",
"u",
".",
"ChocolatesIDs",
"[",
"pos",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}"
] |
// DeleteToManyIDs removes some sweets from a users because they made him very sick
|
[
"DeleteToManyIDs",
"removes",
"some",
"sweets",
"from",
"a",
"users",
"because",
"they",
"made",
"him",
"very",
"sick"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/model/model_user.go#L86-L99
|
15,123 |
manyminds/api2go
|
routing/httprouter.go
|
Handle
|
func (h HTTPRouter) Handle(protocol, route string, handler HandlerFunc) {
wrappedCallback := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
params := map[string]string{}
for _, p := range ps {
params[p.Key] = p.Value
}
handler(w, r, params, make(map[string]interface{}))
}
h.router.Handle(protocol, route, wrappedCallback)
}
|
go
|
func (h HTTPRouter) Handle(protocol, route string, handler HandlerFunc) {
wrappedCallback := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
params := map[string]string{}
for _, p := range ps {
params[p.Key] = p.Value
}
handler(w, r, params, make(map[string]interface{}))
}
h.router.Handle(protocol, route, wrappedCallback)
}
|
[
"func",
"(",
"h",
"HTTPRouter",
")",
"Handle",
"(",
"protocol",
",",
"route",
"string",
",",
"handler",
"HandlerFunc",
")",
"{",
"wrappedCallback",
":=",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"ps",
"httprouter",
".",
"Params",
")",
"{",
"params",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"ps",
"{",
"params",
"[",
"p",
".",
"Key",
"]",
"=",
"p",
".",
"Value",
"\n",
"}",
"\n\n",
"handler",
"(",
"w",
",",
"r",
",",
"params",
",",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
")",
"\n",
"}",
"\n\n",
"h",
".",
"router",
".",
"Handle",
"(",
"protocol",
",",
"route",
",",
"wrappedCallback",
")",
"\n",
"}"
] |
// Handle each method like before and wrap them into julienschmidt handler func style
|
[
"Handle",
"each",
"method",
"like",
"before",
"and",
"wrap",
"them",
"into",
"julienschmidt",
"handler",
"func",
"style"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/routing/httprouter.go#L15-L26
|
15,124 |
manyminds/api2go
|
routing/httprouter.go
|
GetRouteParameter
|
func (h HTTPRouter) GetRouteParameter(r http.Request, param string) string {
path := httprouter.CleanPath(r.URL.Path)
_, params, _ := h.router.Lookup(r.Method, path)
return params.ByName(param)
}
|
go
|
func (h HTTPRouter) GetRouteParameter(r http.Request, param string) string {
path := httprouter.CleanPath(r.URL.Path)
_, params, _ := h.router.Lookup(r.Method, path)
return params.ByName(param)
}
|
[
"func",
"(",
"h",
"HTTPRouter",
")",
"GetRouteParameter",
"(",
"r",
"http",
".",
"Request",
",",
"param",
"string",
")",
"string",
"{",
"path",
":=",
"httprouter",
".",
"CleanPath",
"(",
"r",
".",
"URL",
".",
"Path",
")",
"\n",
"_",
",",
"params",
",",
"_",
":=",
"h",
".",
"router",
".",
"Lookup",
"(",
"r",
".",
"Method",
",",
"path",
")",
"\n",
"return",
"params",
".",
"ByName",
"(",
"param",
")",
"\n",
"}"
] |
// GetRouteParameter implemention will extract the param the julienschmidt way
|
[
"GetRouteParameter",
"implemention",
"will",
"extract",
"the",
"param",
"the",
"julienschmidt",
"way"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/routing/httprouter.go#L40-L44
|
15,125 |
manyminds/api2go
|
context.go
|
Set
|
func (c *APIContext) Set(key string, value interface{}) {
if c.keys == nil {
c.keys = make(map[string]interface{})
}
c.keys[key] = value
}
|
go
|
func (c *APIContext) Set(key string, value interface{}) {
if c.keys == nil {
c.keys = make(map[string]interface{})
}
c.keys[key] = value
}
|
[
"func",
"(",
"c",
"*",
"APIContext",
")",
"Set",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"if",
"c",
".",
"keys",
"==",
"nil",
"{",
"c",
".",
"keys",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"c",
".",
"keys",
"[",
"key",
"]",
"=",
"value",
"\n",
"}"
] |
// Set a string key value in the context
|
[
"Set",
"a",
"string",
"key",
"value",
"in",
"the",
"context"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/context.go#L25-L30
|
15,126 |
manyminds/api2go
|
context.go
|
Get
|
func (c *APIContext) Get(key string) (value interface{}, exists bool) {
if c.keys != nil {
value, exists = c.keys[key]
}
return
}
|
go
|
func (c *APIContext) Get(key string) (value interface{}, exists bool) {
if c.keys != nil {
value, exists = c.keys[key]
}
return
}
|
[
"func",
"(",
"c",
"*",
"APIContext",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"value",
"interface",
"{",
"}",
",",
"exists",
"bool",
")",
"{",
"if",
"c",
".",
"keys",
"!=",
"nil",
"{",
"value",
",",
"exists",
"=",
"c",
".",
"keys",
"[",
"key",
"]",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Get a key value from the context
|
[
"Get",
"a",
"key",
"value",
"from",
"the",
"context"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/context.go#L33-L38
|
15,127 |
manyminds/api2go
|
context.go
|
ContextQueryParams
|
func ContextQueryParams(c *APIContext) map[string][]string {
qp, ok := c.Get("QueryParams")
if ok == false {
qp = make(map[string][]string)
c.Set("QueryParams", qp)
}
return qp.(map[string][]string)
}
|
go
|
func ContextQueryParams(c *APIContext) map[string][]string {
qp, ok := c.Get("QueryParams")
if ok == false {
qp = make(map[string][]string)
c.Set("QueryParams", qp)
}
return qp.(map[string][]string)
}
|
[
"func",
"ContextQueryParams",
"(",
"c",
"*",
"APIContext",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"qp",
",",
"ok",
":=",
"c",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"ok",
"==",
"false",
"{",
"qp",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"c",
".",
"Set",
"(",
"\"",
"\"",
",",
"qp",
")",
"\n",
"}",
"\n",
"return",
"qp",
".",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"}"
] |
// ContextQueryParams fetches the QueryParams if Set
|
[
"ContextQueryParams",
"fetches",
"the",
"QueryParams",
"if",
"Set"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/context.go#L73-L80
|
15,128 |
manyminds/api2go
|
examples/resource/resource_chocolate.go
|
Create
|
func (c ChocolateResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
choc, ok := obj.(model.Chocolate)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id := c.ChocStorage.Insert(choc)
choc.ID = id
return &Response{Res: choc, Code: http.StatusCreated}, nil
}
|
go
|
func (c ChocolateResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
choc, ok := obj.(model.Chocolate)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id := c.ChocStorage.Insert(choc)
choc.ID = id
return &Response{Res: choc, Code: http.StatusCreated}, nil
}
|
[
"func",
"(",
"c",
"ChocolateResource",
")",
"Create",
"(",
"obj",
"interface",
"{",
"}",
",",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"choc",
",",
"ok",
":=",
"obj",
".",
"(",
"model",
".",
"Chocolate",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"api2go",
".",
"NewHTTPError",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n\n",
"id",
":=",
"c",
".",
"ChocStorage",
".",
"Insert",
"(",
"choc",
")",
"\n",
"choc",
".",
"ID",
"=",
"id",
"\n",
"return",
"&",
"Response",
"{",
"Res",
":",
"choc",
",",
"Code",
":",
"http",
".",
"StatusCreated",
"}",
",",
"nil",
"\n",
"}"
] |
// Create a new choc
|
[
"Create",
"a",
"new",
"choc"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_chocolate.go#L52-L61
|
15,129 |
manyminds/api2go
|
examples/resource/resource_chocolate.go
|
Update
|
func (c ChocolateResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
choc, ok := obj.(model.Chocolate)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := c.ChocStorage.Update(choc)
return &Response{Res: choc, Code: http.StatusNoContent}, err
}
|
go
|
func (c ChocolateResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
choc, ok := obj.(model.Chocolate)
if !ok {
return &Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := c.ChocStorage.Update(choc)
return &Response{Res: choc, Code: http.StatusNoContent}, err
}
|
[
"func",
"(",
"c",
"ChocolateResource",
")",
"Update",
"(",
"obj",
"interface",
"{",
"}",
",",
"r",
"api2go",
".",
"Request",
")",
"(",
"api2go",
".",
"Responder",
",",
"error",
")",
"{",
"choc",
",",
"ok",
":=",
"obj",
".",
"(",
"model",
".",
"Chocolate",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"&",
"Response",
"{",
"}",
",",
"api2go",
".",
"NewHTTPError",
"(",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"c",
".",
"ChocStorage",
".",
"Update",
"(",
"choc",
")",
"\n",
"return",
"&",
"Response",
"{",
"Res",
":",
"choc",
",",
"Code",
":",
"http",
".",
"StatusNoContent",
"}",
",",
"err",
"\n",
"}"
] |
// Update a choc
|
[
"Update",
"a",
"choc"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/resource/resource_chocolate.go#L70-L78
|
15,130 |
manyminds/api2go
|
jsonapi/unmarshal.go
|
Unmarshal
|
func Unmarshal(data []byte, target interface{}) error {
if target == nil {
return errors.New("target must not be nil")
}
if reflect.TypeOf(target).Kind() != reflect.Ptr {
return errors.New("target must be a ptr")
}
ctx := &Document{}
err := json.Unmarshal(data, ctx)
if err != nil {
return err
}
if ctx.Data == nil {
return errors.New(`Source JSON is empty and has no "attributes" payload object`)
}
if ctx.Data.DataObject != nil {
return setDataIntoTarget(ctx.Data.DataObject, target)
}
if ctx.Data.DataArray != nil {
targetSlice := reflect.TypeOf(target).Elem()
if targetSlice.Kind() != reflect.Slice {
return fmt.Errorf("Cannot unmarshal array to struct target %s", targetSlice)
}
targetType := targetSlice.Elem()
targetPointer := reflect.ValueOf(target)
targetValue := targetPointer.Elem()
for _, record := range ctx.Data.DataArray {
// check if there already is an entry with the same id in target slice,
// otherwise create a new target and append
var targetRecord, emptyValue reflect.Value
for i := 0; i < targetValue.Len(); i++ {
marshalCasted, ok := targetValue.Index(i).Interface().(MarshalIdentifier)
if !ok {
return errors.New("existing structs must implement interface MarshalIdentifier")
}
if record.ID == marshalCasted.GetID() {
targetRecord = targetValue.Index(i).Addr()
break
}
}
if targetRecord == emptyValue || targetRecord.IsNil() {
targetRecord = reflect.New(targetType)
err := setDataIntoTarget(&record, targetRecord.Interface())
if err != nil {
return err
}
targetValue = reflect.Append(targetValue, targetRecord.Elem())
} else {
err := setDataIntoTarget(&record, targetRecord.Interface())
if err != nil {
return err
}
}
}
targetPointer.Elem().Set(targetValue)
}
return nil
}
|
go
|
func Unmarshal(data []byte, target interface{}) error {
if target == nil {
return errors.New("target must not be nil")
}
if reflect.TypeOf(target).Kind() != reflect.Ptr {
return errors.New("target must be a ptr")
}
ctx := &Document{}
err := json.Unmarshal(data, ctx)
if err != nil {
return err
}
if ctx.Data == nil {
return errors.New(`Source JSON is empty and has no "attributes" payload object`)
}
if ctx.Data.DataObject != nil {
return setDataIntoTarget(ctx.Data.DataObject, target)
}
if ctx.Data.DataArray != nil {
targetSlice := reflect.TypeOf(target).Elem()
if targetSlice.Kind() != reflect.Slice {
return fmt.Errorf("Cannot unmarshal array to struct target %s", targetSlice)
}
targetType := targetSlice.Elem()
targetPointer := reflect.ValueOf(target)
targetValue := targetPointer.Elem()
for _, record := range ctx.Data.DataArray {
// check if there already is an entry with the same id in target slice,
// otherwise create a new target and append
var targetRecord, emptyValue reflect.Value
for i := 0; i < targetValue.Len(); i++ {
marshalCasted, ok := targetValue.Index(i).Interface().(MarshalIdentifier)
if !ok {
return errors.New("existing structs must implement interface MarshalIdentifier")
}
if record.ID == marshalCasted.GetID() {
targetRecord = targetValue.Index(i).Addr()
break
}
}
if targetRecord == emptyValue || targetRecord.IsNil() {
targetRecord = reflect.New(targetType)
err := setDataIntoTarget(&record, targetRecord.Interface())
if err != nil {
return err
}
targetValue = reflect.Append(targetValue, targetRecord.Elem())
} else {
err := setDataIntoTarget(&record, targetRecord.Interface())
if err != nil {
return err
}
}
}
targetPointer.Elem().Set(targetValue)
}
return nil
}
|
[
"func",
"Unmarshal",
"(",
"data",
"[",
"]",
"byte",
",",
"target",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"target",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"reflect",
".",
"TypeOf",
"(",
"target",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ctx",
":=",
"&",
"Document",
"{",
"}",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ctx",
".",
"Data",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"`Source JSON is empty and has no \"attributes\" payload object`",
")",
"\n",
"}",
"\n\n",
"if",
"ctx",
".",
"Data",
".",
"DataObject",
"!=",
"nil",
"{",
"return",
"setDataIntoTarget",
"(",
"ctx",
".",
"Data",
".",
"DataObject",
",",
"target",
")",
"\n",
"}",
"\n\n",
"if",
"ctx",
".",
"Data",
".",
"DataArray",
"!=",
"nil",
"{",
"targetSlice",
":=",
"reflect",
".",
"TypeOf",
"(",
"target",
")",
".",
"Elem",
"(",
")",
"\n",
"if",
"targetSlice",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Slice",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"targetSlice",
")",
"\n",
"}",
"\n",
"targetType",
":=",
"targetSlice",
".",
"Elem",
"(",
")",
"\n",
"targetPointer",
":=",
"reflect",
".",
"ValueOf",
"(",
"target",
")",
"\n",
"targetValue",
":=",
"targetPointer",
".",
"Elem",
"(",
")",
"\n\n",
"for",
"_",
",",
"record",
":=",
"range",
"ctx",
".",
"Data",
".",
"DataArray",
"{",
"// check if there already is an entry with the same id in target slice,",
"// otherwise create a new target and append",
"var",
"targetRecord",
",",
"emptyValue",
"reflect",
".",
"Value",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"targetValue",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"marshalCasted",
",",
"ok",
":=",
"targetValue",
".",
"Index",
"(",
"i",
")",
".",
"Interface",
"(",
")",
".",
"(",
"MarshalIdentifier",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"record",
".",
"ID",
"==",
"marshalCasted",
".",
"GetID",
"(",
")",
"{",
"targetRecord",
"=",
"targetValue",
".",
"Index",
"(",
"i",
")",
".",
"Addr",
"(",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"targetRecord",
"==",
"emptyValue",
"||",
"targetRecord",
".",
"IsNil",
"(",
")",
"{",
"targetRecord",
"=",
"reflect",
".",
"New",
"(",
"targetType",
")",
"\n",
"err",
":=",
"setDataIntoTarget",
"(",
"&",
"record",
",",
"targetRecord",
".",
"Interface",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"targetValue",
"=",
"reflect",
".",
"Append",
"(",
"targetValue",
",",
"targetRecord",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"err",
":=",
"setDataIntoTarget",
"(",
"&",
"record",
",",
"targetRecord",
".",
"Interface",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"targetPointer",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"targetValue",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Unmarshal parses a JSON API compatible JSON and populates the target which
// must implement the `UnmarshalIdentifier` interface.
|
[
"Unmarshal",
"parses",
"a",
"JSON",
"API",
"compatible",
"JSON",
"and",
"populates",
"the",
"target",
"which",
"must",
"implement",
"the",
"UnmarshalIdentifier",
"interface",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/unmarshal.go#L81-L148
|
15,131 |
manyminds/api2go
|
jsonapi/unmarshal.go
|
setRelationshipIDs
|
func setRelationshipIDs(relationships map[string]Relationship, target UnmarshalIdentifier) error {
for name, rel := range relationships {
// if Data is nil, it means that we have an empty toOne relationship
if rel.Data == nil {
castedToOne, ok := target.(UnmarshalToOneRelations)
if !ok {
return fmt.Errorf("struct %s does not implement UnmarshalToOneRelations", reflect.TypeOf(target))
}
castedToOne.SetToOneReferenceID(name, "")
continue
}
// valid toOne case
if rel.Data.DataObject != nil {
castedToOne, ok := target.(UnmarshalToOneRelations)
if !ok {
return fmt.Errorf("struct %s does not implement UnmarshalToOneRelations", reflect.TypeOf(target))
}
err := castedToOne.SetToOneReferenceID(name, rel.Data.DataObject.ID)
if err != nil {
return err
}
}
// valid toMany case
if rel.Data.DataArray != nil {
castedToMany, ok := target.(UnmarshalToManyRelations)
if !ok {
return fmt.Errorf("struct %s does not implement UnmarshalToManyRelations", reflect.TypeOf(target))
}
IDs := make([]string, len(rel.Data.DataArray))
for index, relData := range rel.Data.DataArray {
IDs[index] = relData.ID
}
err := castedToMany.SetToManyReferenceIDs(name, IDs)
if err != nil {
return err
}
}
}
return nil
}
|
go
|
func setRelationshipIDs(relationships map[string]Relationship, target UnmarshalIdentifier) error {
for name, rel := range relationships {
// if Data is nil, it means that we have an empty toOne relationship
if rel.Data == nil {
castedToOne, ok := target.(UnmarshalToOneRelations)
if !ok {
return fmt.Errorf("struct %s does not implement UnmarshalToOneRelations", reflect.TypeOf(target))
}
castedToOne.SetToOneReferenceID(name, "")
continue
}
// valid toOne case
if rel.Data.DataObject != nil {
castedToOne, ok := target.(UnmarshalToOneRelations)
if !ok {
return fmt.Errorf("struct %s does not implement UnmarshalToOneRelations", reflect.TypeOf(target))
}
err := castedToOne.SetToOneReferenceID(name, rel.Data.DataObject.ID)
if err != nil {
return err
}
}
// valid toMany case
if rel.Data.DataArray != nil {
castedToMany, ok := target.(UnmarshalToManyRelations)
if !ok {
return fmt.Errorf("struct %s does not implement UnmarshalToManyRelations", reflect.TypeOf(target))
}
IDs := make([]string, len(rel.Data.DataArray))
for index, relData := range rel.Data.DataArray {
IDs[index] = relData.ID
}
err := castedToMany.SetToManyReferenceIDs(name, IDs)
if err != nil {
return err
}
}
}
return nil
}
|
[
"func",
"setRelationshipIDs",
"(",
"relationships",
"map",
"[",
"string",
"]",
"Relationship",
",",
"target",
"UnmarshalIdentifier",
")",
"error",
"{",
"for",
"name",
",",
"rel",
":=",
"range",
"relationships",
"{",
"// if Data is nil, it means that we have an empty toOne relationship",
"if",
"rel",
".",
"Data",
"==",
"nil",
"{",
"castedToOne",
",",
"ok",
":=",
"target",
".",
"(",
"UnmarshalToOneRelations",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"target",
")",
")",
"\n",
"}",
"\n\n",
"castedToOne",
".",
"SetToOneReferenceID",
"(",
"name",
",",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// valid toOne case",
"if",
"rel",
".",
"Data",
".",
"DataObject",
"!=",
"nil",
"{",
"castedToOne",
",",
"ok",
":=",
"target",
".",
"(",
"UnmarshalToOneRelations",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"target",
")",
")",
"\n",
"}",
"\n",
"err",
":=",
"castedToOne",
".",
"SetToOneReferenceID",
"(",
"name",
",",
"rel",
".",
"Data",
".",
"DataObject",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// valid toMany case",
"if",
"rel",
".",
"Data",
".",
"DataArray",
"!=",
"nil",
"{",
"castedToMany",
",",
"ok",
":=",
"target",
".",
"(",
"UnmarshalToManyRelations",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"target",
")",
")",
"\n",
"}",
"\n",
"IDs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"rel",
".",
"Data",
".",
"DataArray",
")",
")",
"\n",
"for",
"index",
",",
"relData",
":=",
"range",
"rel",
".",
"Data",
".",
"DataArray",
"{",
"IDs",
"[",
"index",
"]",
"=",
"relData",
".",
"ID",
"\n",
"}",
"\n",
"err",
":=",
"castedToMany",
".",
"SetToManyReferenceIDs",
"(",
"name",
",",
"IDs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// extracts all found relationships and set's them via SetToOneReferenceID or
// SetToManyReferenceIDs
|
[
"extracts",
"all",
"found",
"relationships",
"and",
"set",
"s",
"them",
"via",
"SetToOneReferenceID",
"or",
"SetToManyReferenceIDs"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/unmarshal.go#L181-L224
|
15,132 |
manyminds/api2go
|
examples/storage/storage_chocolate.go
|
GetAll
|
func (s ChocolateStorage) GetAll() []model.Chocolate {
result := []model.Chocolate{}
for key := range s.chocolates {
result = append(result, *s.chocolates[key])
}
sort.Sort(byID(result))
return result
}
|
go
|
func (s ChocolateStorage) GetAll() []model.Chocolate {
result := []model.Chocolate{}
for key := range s.chocolates {
result = append(result, *s.chocolates[key])
}
sort.Sort(byID(result))
return result
}
|
[
"func",
"(",
"s",
"ChocolateStorage",
")",
"GetAll",
"(",
")",
"[",
"]",
"model",
".",
"Chocolate",
"{",
"result",
":=",
"[",
"]",
"model",
".",
"Chocolate",
"{",
"}",
"\n",
"for",
"key",
":=",
"range",
"s",
".",
"chocolates",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"*",
"s",
".",
"chocolates",
"[",
"key",
"]",
")",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"byID",
"(",
"result",
")",
")",
"\n",
"return",
"result",
"\n",
"}"
] |
// GetAll of the chocolate
|
[
"GetAll",
"of",
"the",
"chocolate"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/storage/storage_chocolate.go#L38-L46
|
15,133 |
manyminds/api2go
|
examples/storage/storage_chocolate.go
|
GetOne
|
func (s ChocolateStorage) GetOne(id string) (model.Chocolate, error) {
choc, ok := s.chocolates[id]
if ok {
return *choc, nil
}
return model.Chocolate{}, fmt.Errorf("Chocolate for id %s not found", id)
}
|
go
|
func (s ChocolateStorage) GetOne(id string) (model.Chocolate, error) {
choc, ok := s.chocolates[id]
if ok {
return *choc, nil
}
return model.Chocolate{}, fmt.Errorf("Chocolate for id %s not found", id)
}
|
[
"func",
"(",
"s",
"ChocolateStorage",
")",
"GetOne",
"(",
"id",
"string",
")",
"(",
"model",
".",
"Chocolate",
",",
"error",
")",
"{",
"choc",
",",
"ok",
":=",
"s",
".",
"chocolates",
"[",
"id",
"]",
"\n",
"if",
"ok",
"{",
"return",
"*",
"choc",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"model",
".",
"Chocolate",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}"
] |
// GetOne tasty chocolate
|
[
"GetOne",
"tasty",
"chocolate"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/storage/storage_chocolate.go#L49-L56
|
15,134 |
manyminds/api2go
|
examples/storage/storage_chocolate.go
|
Insert
|
func (s *ChocolateStorage) Insert(c model.Chocolate) string {
id := fmt.Sprintf("%d", s.idCount)
c.ID = id
s.chocolates[id] = &c
s.idCount++
return id
}
|
go
|
func (s *ChocolateStorage) Insert(c model.Chocolate) string {
id := fmt.Sprintf("%d", s.idCount)
c.ID = id
s.chocolates[id] = &c
s.idCount++
return id
}
|
[
"func",
"(",
"s",
"*",
"ChocolateStorage",
")",
"Insert",
"(",
"c",
"model",
".",
"Chocolate",
")",
"string",
"{",
"id",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
".",
"idCount",
")",
"\n",
"c",
".",
"ID",
"=",
"id",
"\n",
"s",
".",
"chocolates",
"[",
"id",
"]",
"=",
"&",
"c",
"\n",
"s",
".",
"idCount",
"++",
"\n",
"return",
"id",
"\n",
"}"
] |
// Insert a fresh one
|
[
"Insert",
"a",
"fresh",
"one"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/storage/storage_chocolate.go#L59-L65
|
15,135 |
manyminds/api2go
|
examples/storage/storage_chocolate.go
|
Update
|
func (s *ChocolateStorage) Update(c model.Chocolate) error {
_, exists := s.chocolates[c.ID]
if !exists {
return fmt.Errorf("Chocolate with id %s does not exist", c.ID)
}
s.chocolates[c.ID] = &c
return nil
}
|
go
|
func (s *ChocolateStorage) Update(c model.Chocolate) error {
_, exists := s.chocolates[c.ID]
if !exists {
return fmt.Errorf("Chocolate with id %s does not exist", c.ID)
}
s.chocolates[c.ID] = &c
return nil
}
|
[
"func",
"(",
"s",
"*",
"ChocolateStorage",
")",
"Update",
"(",
"c",
"model",
".",
"Chocolate",
")",
"error",
"{",
"_",
",",
"exists",
":=",
"s",
".",
"chocolates",
"[",
"c",
".",
"ID",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"ID",
")",
"\n",
"}",
"\n",
"s",
".",
"chocolates",
"[",
"c",
".",
"ID",
"]",
"=",
"&",
"c",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Update updates an existing chocolate
|
[
"Update",
"updates",
"an",
"existing",
"chocolate"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/examples/storage/storage_chocolate.go#L79-L87
|
15,136 |
manyminds/api2go
|
jsonapi/data_structs.go
|
UnmarshalJSON
|
func (c *DataContainer) UnmarshalJSON(payload []byte) error {
if bytes.HasPrefix(payload, objectSuffix) {
return json.Unmarshal(payload, &c.DataObject)
}
if bytes.HasPrefix(payload, arraySuffix) {
return json.Unmarshal(payload, &c.DataArray)
}
return errors.New("expected a JSON encoded object or array")
}
|
go
|
func (c *DataContainer) UnmarshalJSON(payload []byte) error {
if bytes.HasPrefix(payload, objectSuffix) {
return json.Unmarshal(payload, &c.DataObject)
}
if bytes.HasPrefix(payload, arraySuffix) {
return json.Unmarshal(payload, &c.DataArray)
}
return errors.New("expected a JSON encoded object or array")
}
|
[
"func",
"(",
"c",
"*",
"DataContainer",
")",
"UnmarshalJSON",
"(",
"payload",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"bytes",
".",
"HasPrefix",
"(",
"payload",
",",
"objectSuffix",
")",
"{",
"return",
"json",
".",
"Unmarshal",
"(",
"payload",
",",
"&",
"c",
".",
"DataObject",
")",
"\n",
"}",
"\n\n",
"if",
"bytes",
".",
"HasPrefix",
"(",
"payload",
",",
"arraySuffix",
")",
"{",
"return",
"json",
".",
"Unmarshal",
"(",
"payload",
",",
"&",
"c",
".",
"DataArray",
")",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// UnmarshalJSON unmarshals the JSON-encoded data to the DataObject field if the
// root element is an object or to the DataArray field for arrays.
|
[
"UnmarshalJSON",
"unmarshals",
"the",
"JSON",
"-",
"encoded",
"data",
"to",
"the",
"DataObject",
"field",
"if",
"the",
"root",
"element",
"is",
"an",
"object",
"or",
"to",
"the",
"DataArray",
"field",
"for",
"arrays",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/data_structs.go#L30-L40
|
15,137 |
manyminds/api2go
|
jsonapi/data_structs.go
|
MarshalJSON
|
func (c *DataContainer) MarshalJSON() ([]byte, error) {
if c.DataArray != nil {
return json.Marshal(c.DataArray)
}
return json.Marshal(c.DataObject)
}
|
go
|
func (c *DataContainer) MarshalJSON() ([]byte, error) {
if c.DataArray != nil {
return json.Marshal(c.DataArray)
}
return json.Marshal(c.DataObject)
}
|
[
"func",
"(",
"c",
"*",
"DataContainer",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"c",
".",
"DataArray",
"!=",
"nil",
"{",
"return",
"json",
".",
"Marshal",
"(",
"c",
".",
"DataArray",
")",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"c",
".",
"DataObject",
")",
"\n",
"}"
] |
// MarshalJSON returns the JSON encoding of the DataArray field or the DataObject
// field. It will return "null" if neither of them is set.
|
[
"MarshalJSON",
"returns",
"the",
"JSON",
"encoding",
"of",
"the",
"DataArray",
"field",
"or",
"the",
"DataObject",
"field",
".",
"It",
"will",
"return",
"null",
"if",
"neither",
"of",
"them",
"is",
"set",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/data_structs.go#L44-L50
|
15,138 |
manyminds/api2go
|
jsonapi/data_structs.go
|
UnmarshalJSON
|
func (l *Link) UnmarshalJSON(payload []byte) error {
// Links may be null in certain cases, mainly noted in the JSONAPI spec
// with pagination links (http://jsonapi.org/format/#fetching-pagination).
if len(payload) == 4 && string(payload) == "null" {
return nil
}
if bytes.HasPrefix(payload, stringSuffix) {
return json.Unmarshal(payload, &l.Href)
}
if bytes.HasPrefix(payload, objectSuffix) {
obj := make(map[string]interface{})
err := json.Unmarshal(payload, &obj)
if err != nil {
return err
}
var ok bool
l.Href, ok = obj["href"].(string)
if !ok {
return errors.New(`link object expects a "href" key`)
}
l.Meta, _ = obj["meta"].(map[string]interface{})
return nil
}
return errors.New("expected a JSON encoded string or object")
}
|
go
|
func (l *Link) UnmarshalJSON(payload []byte) error {
// Links may be null in certain cases, mainly noted in the JSONAPI spec
// with pagination links (http://jsonapi.org/format/#fetching-pagination).
if len(payload) == 4 && string(payload) == "null" {
return nil
}
if bytes.HasPrefix(payload, stringSuffix) {
return json.Unmarshal(payload, &l.Href)
}
if bytes.HasPrefix(payload, objectSuffix) {
obj := make(map[string]interface{})
err := json.Unmarshal(payload, &obj)
if err != nil {
return err
}
var ok bool
l.Href, ok = obj["href"].(string)
if !ok {
return errors.New(`link object expects a "href" key`)
}
l.Meta, _ = obj["meta"].(map[string]interface{})
return nil
}
return errors.New("expected a JSON encoded string or object")
}
|
[
"func",
"(",
"l",
"*",
"Link",
")",
"UnmarshalJSON",
"(",
"payload",
"[",
"]",
"byte",
")",
"error",
"{",
"// Links may be null in certain cases, mainly noted in the JSONAPI spec",
"// with pagination links (http://jsonapi.org/format/#fetching-pagination).",
"if",
"len",
"(",
"payload",
")",
"==",
"4",
"&&",
"string",
"(",
"payload",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"bytes",
".",
"HasPrefix",
"(",
"payload",
",",
"stringSuffix",
")",
"{",
"return",
"json",
".",
"Unmarshal",
"(",
"payload",
",",
"&",
"l",
".",
"Href",
")",
"\n",
"}",
"\n\n",
"if",
"bytes",
".",
"HasPrefix",
"(",
"payload",
",",
"objectSuffix",
")",
"{",
"obj",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"payload",
",",
"&",
"obj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"ok",
"bool",
"\n",
"l",
".",
"Href",
",",
"ok",
"=",
"obj",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"`link object expects a \"href\" key`",
")",
"\n",
"}",
"\n\n",
"l",
".",
"Meta",
",",
"_",
"=",
"obj",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// UnmarshalJSON marshals a string value into the Href field or marshals an
// object value into the whole struct.
|
[
"UnmarshalJSON",
"marshals",
"a",
"string",
"value",
"into",
"the",
"Href",
"field",
"or",
"marshals",
"an",
"object",
"value",
"into",
"the",
"whole",
"struct",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/data_structs.go#L60-L88
|
15,139 |
manyminds/api2go
|
jsonapi/data_structs.go
|
MarshalJSON
|
func (l Link) MarshalJSON() ([]byte, error) {
if l.Empty() {
return json.Marshal(nil)
}
if len(l.Meta) == 0 {
return json.Marshal(l.Href)
}
return json.Marshal(map[string]interface{}{
"href": l.Href,
"meta": l.Meta,
})
}
|
go
|
func (l Link) MarshalJSON() ([]byte, error) {
if l.Empty() {
return json.Marshal(nil)
}
if len(l.Meta) == 0 {
return json.Marshal(l.Href)
}
return json.Marshal(map[string]interface{}{
"href": l.Href,
"meta": l.Meta,
})
}
|
[
"func",
"(",
"l",
"Link",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"l",
".",
"Empty",
"(",
")",
"{",
"return",
"json",
".",
"Marshal",
"(",
"nil",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"l",
".",
"Meta",
")",
"==",
"0",
"{",
"return",
"json",
".",
"Marshal",
"(",
"l",
".",
"Href",
")",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"l",
".",
"Href",
",",
"\"",
"\"",
":",
"l",
".",
"Meta",
",",
"}",
")",
"\n",
"}"
] |
// MarshalJSON returns the JSON encoding of only the Href field if the Meta
// field is empty, otherwise it marshals the whole struct.
|
[
"MarshalJSON",
"returns",
"the",
"JSON",
"encoding",
"of",
"only",
"the",
"Href",
"field",
"if",
"the",
"Meta",
"field",
"is",
"empty",
"otherwise",
"it",
"marshals",
"the",
"whole",
"struct",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/data_structs.go#L92-L103
|
15,140 |
manyminds/api2go
|
error.go
|
marshalHTTPError
|
func marshalHTTPError(input HTTPError) string {
if len(input.Errors) == 0 {
input.Errors = []Error{{Title: input.msg, Status: strconv.Itoa(input.status)}}
}
data, err := json.Marshal(input)
if err != nil {
log.Println(err)
return "{}"
}
return string(data)
}
|
go
|
func marshalHTTPError(input HTTPError) string {
if len(input.Errors) == 0 {
input.Errors = []Error{{Title: input.msg, Status: strconv.Itoa(input.status)}}
}
data, err := json.Marshal(input)
if err != nil {
log.Println(err)
return "{}"
}
return string(data)
}
|
[
"func",
"marshalHTTPError",
"(",
"input",
"HTTPError",
")",
"string",
"{",
"if",
"len",
"(",
"input",
".",
"Errors",
")",
"==",
"0",
"{",
"input",
".",
"Errors",
"=",
"[",
"]",
"Error",
"{",
"{",
"Title",
":",
"input",
".",
"msg",
",",
"Status",
":",
"strconv",
".",
"Itoa",
"(",
"input",
".",
"status",
")",
"}",
"}",
"\n",
"}",
"\n\n",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"input",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"data",
")",
"\n",
"}"
] |
// marshalHTTPError marshals an internal httpError
|
[
"marshalHTTPError",
"marshals",
"an",
"internal",
"httpError"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/error.go#L54-L67
|
15,141 |
manyminds/api2go
|
error.go
|
Error
|
func (e HTTPError) Error() string {
msg := fmt.Sprintf("http error (%d) %s and %d more errors", e.status, e.msg, len(e.Errors))
if e.err != nil {
msg += ", " + e.err.Error()
}
return msg
}
|
go
|
func (e HTTPError) Error() string {
msg := fmt.Sprintf("http error (%d) %s and %d more errors", e.status, e.msg, len(e.Errors))
if e.err != nil {
msg += ", " + e.err.Error()
}
return msg
}
|
[
"func",
"(",
"e",
"HTTPError",
")",
"Error",
"(",
")",
"string",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"e",
".",
"status",
",",
"e",
".",
"msg",
",",
"len",
"(",
"e",
".",
"Errors",
")",
")",
"\n",
"if",
"e",
".",
"err",
"!=",
"nil",
"{",
"msg",
"+=",
"\"",
"\"",
"+",
"e",
".",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"msg",
"\n",
"}"
] |
// Error returns a nice string represenation including the status
|
[
"Error",
"returns",
"a",
"nice",
"string",
"represenation",
"including",
"the",
"status"
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/error.go#L77-L84
|
15,142 |
manyminds/api2go
|
jsonapi/helpers.go
|
Jsonify
|
func Jsonify(s string) string {
if s == "" {
return ""
}
if commonInitialisms[s] {
return strings.ToLower(s)
}
rs := []rune(s)
rs[0] = unicode.ToLower(rs[0])
return string(rs)
}
|
go
|
func Jsonify(s string) string {
if s == "" {
return ""
}
if commonInitialisms[s] {
return strings.ToLower(s)
}
rs := []rune(s)
rs[0] = unicode.ToLower(rs[0])
return string(rs)
}
|
[
"func",
"Jsonify",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"commonInitialisms",
"[",
"s",
"]",
"{",
"return",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"}",
"\n\n",
"rs",
":=",
"[",
"]",
"rune",
"(",
"s",
")",
"\n",
"rs",
"[",
"0",
"]",
"=",
"unicode",
".",
"ToLower",
"(",
"rs",
"[",
"0",
"]",
")",
"\n\n",
"return",
"string",
"(",
"rs",
")",
"\n",
"}"
] |
// Jsonify returns a JSON formatted key name from a go struct field name.
|
[
"Jsonify",
"returns",
"a",
"JSON",
"formatted",
"key",
"name",
"from",
"a",
"go",
"struct",
"field",
"name",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/helpers.go#L47-L60
|
15,143 |
manyminds/api2go
|
jsonapi/marshal.go
|
MarshalWithURLs
|
func MarshalWithURLs(data interface{}, information ServerInformation) ([]byte, error) {
document, err := MarshalToStruct(data, information)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
|
go
|
func MarshalWithURLs(data interface{}, information ServerInformation) ([]byte, error) {
document, err := MarshalToStruct(data, information)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
|
[
"func",
"MarshalWithURLs",
"(",
"data",
"interface",
"{",
"}",
",",
"information",
"ServerInformation",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"document",
",",
"err",
":=",
"MarshalToStruct",
"(",
"data",
",",
"information",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"document",
")",
"\n",
"}"
] |
// MarshalWithURLs can be used to pass along a ServerInformation implementor.
|
[
"MarshalWithURLs",
"can",
"be",
"used",
"to",
"pass",
"along",
"a",
"ServerInformation",
"implementor",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/marshal.go#L105-L112
|
15,144 |
manyminds/api2go
|
jsonapi/marshal.go
|
Marshal
|
func Marshal(data interface{}) ([]byte, error) {
document, err := MarshalToStruct(data, nil)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
|
go
|
func Marshal(data interface{}) ([]byte, error) {
document, err := MarshalToStruct(data, nil)
if err != nil {
return nil, err
}
return json.Marshal(document)
}
|
[
"func",
"Marshal",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"document",
",",
"err",
":=",
"MarshalToStruct",
"(",
"data",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"document",
")",
"\n",
"}"
] |
// Marshal wraps data in a Document and returns its JSON encoding.
//
// Data can be a struct, a pointer to a struct or a slice of structs. All structs
// must at least implement the `MarshalIdentifier` interface.
|
[
"Marshal",
"wraps",
"data",
"in",
"a",
"Document",
"and",
"returns",
"its",
"JSON",
"encoding",
".",
"Data",
"can",
"be",
"a",
"struct",
"a",
"pointer",
"to",
"a",
"struct",
"or",
"a",
"slice",
"of",
"structs",
".",
"All",
"structs",
"must",
"at",
"least",
"implement",
"the",
"MarshalIdentifier",
"interface",
"."
] |
d4f7fae65b4bba69a8214a630249da9e16545343
|
https://github.com/manyminds/api2go/blob/d4f7fae65b4bba69a8214a630249da9e16545343/jsonapi/marshal.go#L118-L125
|
15,145 |
go-playground/locales
|
ga_IE/ga_IE.go
|
FmtTimeMedium
|
func (ga *ga_IE) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ga.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ga.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
|
go
|
func (ga *ga_IE) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ga.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ga.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
|
[
"func",
"(",
"ga",
"*",
"ga_IE",
")",
"FmtTimeMedium",
"(",
"t",
"time",
".",
"Time",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"32",
")",
"\n\n",
"if",
"t",
".",
"Hour",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Hour",
"(",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"ga",
".",
"timeSeparator",
"...",
")",
"\n\n",
"if",
"t",
".",
"Minute",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Minute",
"(",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"ga",
".",
"timeSeparator",
"...",
")",
"\n\n",
"if",
"t",
".",
"Second",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Second",
"(",
")",
")",
",",
"10",
")",
"\n\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
// FmtTimeMedium returns the medium time representation of 't' for 'ga_IE'
|
[
"FmtTimeMedium",
"returns",
"the",
"medium",
"time",
"representation",
"of",
"t",
"for",
"ga_IE"
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/ga_IE/ga_IE.go#L566-L591
|
15,146 |
go-playground/locales
|
rof_TZ/rof_TZ.go
|
FmtTimeFull
|
func (rof *rof_TZ) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, rof.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, rof.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
if btz, ok := rof.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
return string(b)
}
|
go
|
func (rof *rof_TZ) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, rof.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, rof.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
if btz, ok := rof.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
return string(b)
}
|
[
"func",
"(",
"rof",
"*",
"rof_TZ",
")",
"FmtTimeFull",
"(",
"t",
"time",
".",
"Time",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"32",
")",
"\n\n",
"if",
"t",
".",
"Hour",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Hour",
"(",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"rof",
".",
"timeSeparator",
"...",
")",
"\n\n",
"if",
"t",
".",
"Minute",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Minute",
"(",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"rof",
".",
"timeSeparator",
"...",
")",
"\n\n",
"if",
"t",
".",
"Second",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Second",
"(",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"[",
"]",
"byte",
"{",
"0x20",
"}",
"...",
")",
"\n\n",
"tz",
",",
"_",
":=",
"t",
".",
"Zone",
"(",
")",
"\n\n",
"if",
"btz",
",",
"ok",
":=",
"rof",
".",
"timezones",
"[",
"tz",
"]",
";",
"ok",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"btz",
"...",
")",
"\n",
"}",
"else",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"tz",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
// FmtTimeFull returns the full time representation of 't' for 'rof_TZ'
|
[
"FmtTimeFull",
"returns",
"the",
"full",
"time",
"representation",
"of",
"t",
"for",
"rof_TZ"
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/rof_TZ/rof_TZ.go#L498-L532
|
15,147 |
go-playground/locales
|
tzm/tzm.go
|
FmtTimeLong
|
func (tzm *tzm) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
return string(b)
}
|
go
|
func (tzm *tzm) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
return string(b)
}
|
[
"func",
"(",
"tzm",
"*",
"tzm",
")",
"FmtTimeLong",
"(",
"t",
"time",
".",
"Time",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"32",
")",
"\n\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
// FmtTimeLong returns the long time representation of 't' for 'tzm'
|
[
"FmtTimeLong",
"returns",
"the",
"long",
"time",
"representation",
"of",
"t",
"for",
"tzm"
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/tzm/tzm.go#L442-L447
|
15,148 |
go-playground/locales
|
vun_TZ/vun_TZ.go
|
FmtDateShort
|
func (vun *vun_TZ) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Day() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
if t.Month() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
|
go
|
func (vun *vun_TZ) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Day() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
if t.Month() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
|
[
"func",
"(",
"vun",
"*",
"vun_TZ",
")",
"FmtDateShort",
"(",
"t",
"time",
".",
"Time",
")",
"string",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"32",
")",
"\n\n",
"if",
"t",
".",
"Day",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Day",
"(",
")",
")",
",",
"10",
")",
"\n",
"b",
"=",
"append",
"(",
"b",
",",
"[",
"]",
"byte",
"{",
"0x2f",
"}",
"...",
")",
"\n\n",
"if",
"t",
".",
"Month",
"(",
")",
"<",
"10",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"'0'",
")",
"\n",
"}",
"\n\n",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Month",
"(",
")",
")",
",",
"10",
")",
"\n\n",
"b",
"=",
"append",
"(",
"b",
",",
"[",
"]",
"byte",
"{",
"0x2f",
"}",
"...",
")",
"\n\n",
"if",
"t",
".",
"Year",
"(",
")",
">",
"0",
"{",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"t",
".",
"Year",
"(",
")",
")",
",",
"10",
")",
"\n",
"}",
"else",
"{",
"b",
"=",
"strconv",
".",
"AppendInt",
"(",
"b",
",",
"int64",
"(",
"-",
"t",
".",
"Year",
"(",
")",
")",
",",
"10",
")",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
// FmtDateShort returns the short date representation of 't' for 'vun_TZ'
|
[
"FmtDateShort",
"returns",
"the",
"short",
"date",
"representation",
"of",
"t",
"for",
"vun_TZ"
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/vun_TZ/vun_TZ.go#L329-L355
|
15,149 |
go-playground/locales
|
rules.go
|
String
|
func (p PluralRule) String() string {
switch p {
case PluralRuleZero:
return pluralsString[7:11]
case PluralRuleOne:
return pluralsString[11:14]
case PluralRuleTwo:
return pluralsString[14:17]
case PluralRuleFew:
return pluralsString[17:20]
case PluralRuleMany:
return pluralsString[20:24]
case PluralRuleOther:
return pluralsString[24:]
default:
return pluralsString[:7]
}
}
|
go
|
func (p PluralRule) String() string {
switch p {
case PluralRuleZero:
return pluralsString[7:11]
case PluralRuleOne:
return pluralsString[11:14]
case PluralRuleTwo:
return pluralsString[14:17]
case PluralRuleFew:
return pluralsString[17:20]
case PluralRuleMany:
return pluralsString[20:24]
case PluralRuleOther:
return pluralsString[24:]
default:
return pluralsString[:7]
}
}
|
[
"func",
"(",
"p",
"PluralRule",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"p",
"{",
"case",
"PluralRuleZero",
":",
"return",
"pluralsString",
"[",
"7",
":",
"11",
"]",
"\n",
"case",
"PluralRuleOne",
":",
"return",
"pluralsString",
"[",
"11",
":",
"14",
"]",
"\n",
"case",
"PluralRuleTwo",
":",
"return",
"pluralsString",
"[",
"14",
":",
"17",
"]",
"\n",
"case",
"PluralRuleFew",
":",
"return",
"pluralsString",
"[",
"17",
":",
"20",
"]",
"\n",
"case",
"PluralRuleMany",
":",
"return",
"pluralsString",
"[",
"20",
":",
"24",
"]",
"\n",
"case",
"PluralRuleOther",
":",
"return",
"pluralsString",
"[",
"24",
":",
"]",
"\n",
"default",
":",
"return",
"pluralsString",
"[",
":",
"7",
"]",
"\n",
"}",
"\n",
"}"
] |
// String returns the string value of PluralRule
|
[
"String",
"returns",
"the",
"string",
"value",
"of",
"PluralRule"
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/rules.go#L158-L176
|
15,150 |
go-playground/locales
|
rules.go
|
F
|
func F(n float64, v uint64) (f int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then f will be zero
// otherwise need to parse
if len(s) != 1 {
// ignoring error, because it can't fail as we generated
// the string internally from a real number
f, _ = strconv.ParseInt(s[2:], 10, 64)
}
return
}
|
go
|
func F(n float64, v uint64) (f int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then f will be zero
// otherwise need to parse
if len(s) != 1 {
// ignoring error, because it can't fail as we generated
// the string internally from a real number
f, _ = strconv.ParseInt(s[2:], 10, 64)
}
return
}
|
[
"func",
"F",
"(",
"n",
"float64",
",",
"v",
"uint64",
")",
"(",
"f",
"int64",
")",
"{",
"s",
":=",
"strconv",
".",
"FormatFloat",
"(",
"n",
"-",
"float64",
"(",
"int64",
"(",
"n",
")",
")",
",",
"'f'",
",",
"int",
"(",
"v",
")",
",",
"64",
")",
"\n\n",
"// with either be '0' or '0.xxxx', so if 1 then f will be zero",
"// otherwise need to parse",
"if",
"len",
"(",
"s",
")",
"!=",
"1",
"{",
"// ignoring error, because it can't fail as we generated",
"// the string internally from a real number",
"f",
",",
"_",
"=",
"strconv",
".",
"ParseInt",
"(",
"s",
"[",
"2",
":",
"]",
",",
"10",
",",
"64",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// F returns the visible fractional digits in N, with trailing zeros.
|
[
"F",
"returns",
"the",
"visible",
"fractional",
"digits",
"in",
"N",
"with",
"trailing",
"zeros",
"."
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/rules.go#L252-L266
|
15,151 |
go-playground/locales
|
rules.go
|
T
|
func T(n float64, v uint64) (t int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then t will be zero
// otherwise need to parse
if len(s) != 1 {
s = s[2:]
end := len(s) + 1
for i := end; i >= 0; i-- {
if s[i] != '0' {
end = i + 1
break
}
}
// ignoring error, because it can't fail as we generated
// the string internally from a real number
t, _ = strconv.ParseInt(s[:end], 10, 64)
}
return
}
|
go
|
func T(n float64, v uint64) (t int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then t will be zero
// otherwise need to parse
if len(s) != 1 {
s = s[2:]
end := len(s) + 1
for i := end; i >= 0; i-- {
if s[i] != '0' {
end = i + 1
break
}
}
// ignoring error, because it can't fail as we generated
// the string internally from a real number
t, _ = strconv.ParseInt(s[:end], 10, 64)
}
return
}
|
[
"func",
"T",
"(",
"n",
"float64",
",",
"v",
"uint64",
")",
"(",
"t",
"int64",
")",
"{",
"s",
":=",
"strconv",
".",
"FormatFloat",
"(",
"n",
"-",
"float64",
"(",
"int64",
"(",
"n",
")",
")",
",",
"'f'",
",",
"int",
"(",
"v",
")",
",",
"64",
")",
"\n\n",
"// with either be '0' or '0.xxxx', so if 1 then t will be zero",
"// otherwise need to parse",
"if",
"len",
"(",
"s",
")",
"!=",
"1",
"{",
"s",
"=",
"s",
"[",
"2",
":",
"]",
"\n",
"end",
":=",
"len",
"(",
"s",
")",
"+",
"1",
"\n\n",
"for",
"i",
":=",
"end",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"if",
"s",
"[",
"i",
"]",
"!=",
"'0'",
"{",
"end",
"=",
"i",
"+",
"1",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// ignoring error, because it can't fail as we generated",
"// the string internally from a real number",
"t",
",",
"_",
"=",
"strconv",
".",
"ParseInt",
"(",
"s",
"[",
":",
"end",
"]",
",",
"10",
",",
"64",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] |
// T returns the visible fractional digits in N, without trailing zeros.
|
[
"T",
"returns",
"the",
"visible",
"fractional",
"digits",
"in",
"N",
"without",
"trailing",
"zeros",
"."
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/rules.go#L269-L293
|
15,152 |
go-playground/locales
|
cmd/generate_resources.go
|
pluralStringToInt
|
func pluralStringToInt(plural string) locales.PluralRule {
switch plural {
case "zero":
return locales.PluralRuleZero
case "one":
return locales.PluralRuleOne
case "two":
return locales.PluralRuleTwo
case "few":
return locales.PluralRuleFew
case "many":
return locales.PluralRuleMany
case "other":
return locales.PluralRuleOther
default:
return locales.PluralRuleUnknown
}
}
|
go
|
func pluralStringToInt(plural string) locales.PluralRule {
switch plural {
case "zero":
return locales.PluralRuleZero
case "one":
return locales.PluralRuleOne
case "two":
return locales.PluralRuleTwo
case "few":
return locales.PluralRuleFew
case "many":
return locales.PluralRuleMany
case "other":
return locales.PluralRuleOther
default:
return locales.PluralRuleUnknown
}
}
|
[
"func",
"pluralStringToInt",
"(",
"plural",
"string",
")",
"locales",
".",
"PluralRule",
"{",
"switch",
"plural",
"{",
"case",
"\"",
"\"",
":",
"return",
"locales",
".",
"PluralRuleZero",
"\n",
"case",
"\"",
"\"",
":",
"return",
"locales",
".",
"PluralRuleOne",
"\n",
"case",
"\"",
"\"",
":",
"return",
"locales",
".",
"PluralRuleTwo",
"\n",
"case",
"\"",
"\"",
":",
"return",
"locales",
".",
"PluralRuleFew",
"\n",
"case",
"\"",
"\"",
":",
"return",
"locales",
".",
"PluralRuleMany",
"\n",
"case",
"\"",
"\"",
":",
"return",
"locales",
".",
"PluralRuleOther",
"\n",
"default",
":",
"return",
"locales",
".",
"PluralRuleUnknown",
"\n",
"}",
"\n",
"}"
] |
// pluralStringToInt returns the enum value of 'plural' provided
|
[
"pluralStringToInt",
"returns",
"the",
"enum",
"value",
"of",
"plural",
"provided"
] |
630ebbb602847eba93e75ae38bbc7bb7abcf1ff3
|
https://github.com/go-playground/locales/blob/630ebbb602847eba93e75ae38bbc7bb7abcf1ff3/cmd/generate_resources.go#L2855-L2873
|
15,153 |
intel-go/cpuid
|
cpuid_amd64.go
|
leaf0x80000004
|
func leaf0x80000004() {
if maxExtendedInputValue < 0x80000004 {
return
}
ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000002, 0)))
ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000003, 0)))
ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000004, 0)))
}
|
go
|
func leaf0x80000004() {
if maxExtendedInputValue < 0x80000004 {
return
}
ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000002, 0)))
ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000003, 0)))
ProcessorBrandString += string(int32sToBytes(cpuid_low(0x80000004, 0)))
}
|
[
"func",
"leaf0x80000004",
"(",
")",
"{",
"if",
"maxExtendedInputValue",
"<",
"0x80000004",
"{",
"return",
"\n",
"}",
"\n\n",
"ProcessorBrandString",
"+=",
"string",
"(",
"int32sToBytes",
"(",
"cpuid_low",
"(",
"0x80000002",
",",
"0",
")",
")",
")",
"\n",
"ProcessorBrandString",
"+=",
"string",
"(",
"int32sToBytes",
"(",
"cpuid_low",
"(",
"0x80000003",
",",
"0",
")",
")",
")",
"\n",
"ProcessorBrandString",
"+=",
"string",
"(",
"int32sToBytes",
"(",
"cpuid_low",
"(",
"0x80000004",
",",
"0",
")",
")",
")",
"\n",
"}"
] |
// leaf0x80000004 looks at the Processor Brand String in leaves 0x80000002 through 0x80000004
|
[
"leaf0x80000004",
"looks",
"at",
"the",
"Processor",
"Brand",
"String",
"in",
"leaves",
"0x80000002",
"through",
"0x80000004"
] |
1a4a6f06a1c643c8fbd339bd61d980960627d09e
|
https://github.com/intel-go/cpuid/blob/1a4a6f06a1c643c8fbd339bd61d980960627d09e/cpuid_amd64.go#L227-L235
|
15,154 |
chaseadamsio/goorgeous
|
header.go
|
ExtractOrgHeaders
|
func ExtractOrgHeaders(r *bufio.Reader) (fm []byte, err error) {
var out bytes.Buffer
endOfHeaders := true
for endOfHeaders {
p, err := r.Peek(2)
if err != nil {
return nil, err
}
if !charMatches(p[0], '#') && !charMatches(p[1], '+') {
endOfHeaders = false
break
}
line, _, err := r.ReadLine()
if err != nil {
return nil, err
}
out.Write(line)
out.WriteByte('\n')
}
return out.Bytes(), nil
}
|
go
|
func ExtractOrgHeaders(r *bufio.Reader) (fm []byte, err error) {
var out bytes.Buffer
endOfHeaders := true
for endOfHeaders {
p, err := r.Peek(2)
if err != nil {
return nil, err
}
if !charMatches(p[0], '#') && !charMatches(p[1], '+') {
endOfHeaders = false
break
}
line, _, err := r.ReadLine()
if err != nil {
return nil, err
}
out.Write(line)
out.WriteByte('\n')
}
return out.Bytes(), nil
}
|
[
"func",
"ExtractOrgHeaders",
"(",
"r",
"*",
"bufio",
".",
"Reader",
")",
"(",
"fm",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"var",
"out",
"bytes",
".",
"Buffer",
"\n",
"endOfHeaders",
":=",
"true",
"\n",
"for",
"endOfHeaders",
"{",
"p",
",",
"err",
":=",
"r",
".",
"Peek",
"(",
"2",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"charMatches",
"(",
"p",
"[",
"0",
"]",
",",
"'#'",
")",
"&&",
"!",
"charMatches",
"(",
"p",
"[",
"1",
"]",
",",
"'+'",
")",
"{",
"endOfHeaders",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n",
"line",
",",
"_",
",",
"err",
":=",
"r",
".",
"ReadLine",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"out",
".",
"Write",
"(",
"line",
")",
"\n",
"out",
".",
"WriteByte",
"(",
"'\\n'",
")",
"\n",
"}",
"\n",
"return",
"out",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// ExtractOrgHeaders finds and returns all of the headers
// from a bufio.Reader and returns them as their own byte slice
|
[
"ExtractOrgHeaders",
"finds",
"and",
"returns",
"all",
"of",
"the",
"headers",
"from",
"a",
"bufio",
".",
"Reader",
"and",
"returns",
"them",
"as",
"their",
"own",
"byte",
"slice"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/header.go#L12-L32
|
15,155 |
chaseadamsio/goorgeous
|
header.go
|
OrgHeaders
|
func OrgHeaders(input []byte) (map[string]interface{}, error) {
out := make(map[string]interface{})
scanner := bufio.NewScanner(bytes.NewReader(input))
for scanner.Scan() {
data := scanner.Bytes()
if !charMatches(data[0], '#') && !charMatches(data[1], '+') {
return out, nil
}
matches := reHeader.FindSubmatch(data)
if len(matches) < 3 {
continue
}
key := string(matches[1])
val := matches[2]
switch {
case strings.ToLower(key) == "tags" || strings.ToLower(key) == "categories" || strings.ToLower(key) == "aliases":
bTags := bytes.Split(val, []byte(" "))
tags := make([]string, len(bTags))
for idx, tag := range bTags {
tags[idx] = string(tag)
}
out[key] = tags
default:
out[key] = string(val)
}
}
return out, nil
}
|
go
|
func OrgHeaders(input []byte) (map[string]interface{}, error) {
out := make(map[string]interface{})
scanner := bufio.NewScanner(bytes.NewReader(input))
for scanner.Scan() {
data := scanner.Bytes()
if !charMatches(data[0], '#') && !charMatches(data[1], '+') {
return out, nil
}
matches := reHeader.FindSubmatch(data)
if len(matches) < 3 {
continue
}
key := string(matches[1])
val := matches[2]
switch {
case strings.ToLower(key) == "tags" || strings.ToLower(key) == "categories" || strings.ToLower(key) == "aliases":
bTags := bytes.Split(val, []byte(" "))
tags := make([]string, len(bTags))
for idx, tag := range bTags {
tags[idx] = string(tag)
}
out[key] = tags
default:
out[key] = string(val)
}
}
return out, nil
}
|
[
"func",
"OrgHeaders",
"(",
"input",
"[",
"]",
"byte",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"bytes",
".",
"NewReader",
"(",
"input",
")",
")",
"\n\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"data",
":=",
"scanner",
".",
"Bytes",
"(",
")",
"\n",
"if",
"!",
"charMatches",
"(",
"data",
"[",
"0",
"]",
",",
"'#'",
")",
"&&",
"!",
"charMatches",
"(",
"data",
"[",
"1",
"]",
",",
"'+'",
")",
"{",
"return",
"out",
",",
"nil",
"\n",
"}",
"\n",
"matches",
":=",
"reHeader",
".",
"FindSubmatch",
"(",
"data",
")",
"\n\n",
"if",
"len",
"(",
"matches",
")",
"<",
"3",
"{",
"continue",
"\n",
"}",
"\n\n",
"key",
":=",
"string",
"(",
"matches",
"[",
"1",
"]",
")",
"\n",
"val",
":=",
"matches",
"[",
"2",
"]",
"\n",
"switch",
"{",
"case",
"strings",
".",
"ToLower",
"(",
"key",
")",
"==",
"\"",
"\"",
"||",
"strings",
".",
"ToLower",
"(",
"key",
")",
"==",
"\"",
"\"",
"||",
"strings",
".",
"ToLower",
"(",
"key",
")",
"==",
"\"",
"\"",
":",
"bTags",
":=",
"bytes",
".",
"Split",
"(",
"val",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"tags",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"bTags",
")",
")",
"\n",
"for",
"idx",
",",
"tag",
":=",
"range",
"bTags",
"{",
"tags",
"[",
"idx",
"]",
"=",
"string",
"(",
"tag",
")",
"\n",
"}",
"\n",
"out",
"[",
"key",
"]",
"=",
"tags",
"\n",
"default",
":",
"out",
"[",
"key",
"]",
"=",
"string",
"(",
"val",
")",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n\n",
"}"
] |
// OrgHeaders find all of the headers from a byte slice and returns
// them as a map of string interface
|
[
"OrgHeaders",
"find",
"all",
"of",
"the",
"headers",
"from",
"a",
"byte",
"slice",
"and",
"returns",
"them",
"as",
"a",
"map",
"of",
"string",
"interface"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/header.go#L38-L70
|
15,156 |
chaseadamsio/goorgeous
|
goorgeous.go
|
NewParser
|
func NewParser(renderer blackfriday.Renderer) *parser {
p := new(parser)
p.r = renderer
p.inlineCallback['='] = generateVerbatim
p.inlineCallback['~'] = generateCode
p.inlineCallback['/'] = generateEmphasis
p.inlineCallback['_'] = generateUnderline
p.inlineCallback['*'] = generateBold
p.inlineCallback['+'] = generateStrikethrough
p.inlineCallback['['] = generateLinkOrImg
return p
}
|
go
|
func NewParser(renderer blackfriday.Renderer) *parser {
p := new(parser)
p.r = renderer
p.inlineCallback['='] = generateVerbatim
p.inlineCallback['~'] = generateCode
p.inlineCallback['/'] = generateEmphasis
p.inlineCallback['_'] = generateUnderline
p.inlineCallback['*'] = generateBold
p.inlineCallback['+'] = generateStrikethrough
p.inlineCallback['['] = generateLinkOrImg
return p
}
|
[
"func",
"NewParser",
"(",
"renderer",
"blackfriday",
".",
"Renderer",
")",
"*",
"parser",
"{",
"p",
":=",
"new",
"(",
"parser",
")",
"\n",
"p",
".",
"r",
"=",
"renderer",
"\n\n",
"p",
".",
"inlineCallback",
"[",
"'='",
"]",
"=",
"generateVerbatim",
"\n",
"p",
".",
"inlineCallback",
"[",
"'~'",
"]",
"=",
"generateCode",
"\n",
"p",
".",
"inlineCallback",
"[",
"'/'",
"]",
"=",
"generateEmphasis",
"\n",
"p",
".",
"inlineCallback",
"[",
"'_'",
"]",
"=",
"generateUnderline",
"\n",
"p",
".",
"inlineCallback",
"[",
"'*'",
"]",
"=",
"generateBold",
"\n",
"p",
".",
"inlineCallback",
"[",
"'+'",
"]",
"=",
"generateStrikethrough",
"\n",
"p",
".",
"inlineCallback",
"[",
"'['",
"]",
"=",
"generateLinkOrImg",
"\n\n",
"return",
"p",
"\n",
"}"
] |
// NewParser returns a new parser with the inlineCallbacks required for org content
|
[
"NewParser",
"returns",
"a",
"new",
"parser",
"with",
"the",
"inlineCallbacks",
"required",
"for",
"org",
"content"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/goorgeous.go#L26-L39
|
15,157 |
chaseadamsio/goorgeous
|
goorgeous.go
|
OrgCommon
|
func OrgCommon(input []byte) []byte {
renderer := blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML, "", "")
return OrgOptions(input, renderer)
}
|
go
|
func OrgCommon(input []byte) []byte {
renderer := blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML, "", "")
return OrgOptions(input, renderer)
}
|
[
"func",
"OrgCommon",
"(",
"input",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"renderer",
":=",
"blackfriday",
".",
"HtmlRenderer",
"(",
"blackfriday",
".",
"HTML_USE_XHTML",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"OrgOptions",
"(",
"input",
",",
"renderer",
")",
"\n",
"}"
] |
// OrgCommon is the easiest way to parse a byte slice of org content and makes assumptions
// that the caller wants to use blackfriday's HTMLRenderer with XHTML
|
[
"OrgCommon",
"is",
"the",
"easiest",
"way",
"to",
"parse",
"a",
"byte",
"slice",
"of",
"org",
"content",
"and",
"makes",
"assumptions",
"that",
"the",
"caller",
"wants",
"to",
"use",
"blackfriday",
"s",
"HTMLRenderer",
"with",
"XHTML"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/goorgeous.go#L43-L46
|
15,158 |
chaseadamsio/goorgeous
|
goorgeous.go
|
Org
|
func Org(input []byte, renderer blackfriday.Renderer) []byte {
return OrgOptions(input, renderer)
}
|
go
|
func Org(input []byte, renderer blackfriday.Renderer) []byte {
return OrgOptions(input, renderer)
}
|
[
"func",
"Org",
"(",
"input",
"[",
"]",
"byte",
",",
"renderer",
"blackfriday",
".",
"Renderer",
")",
"[",
"]",
"byte",
"{",
"return",
"OrgOptions",
"(",
"input",
",",
"renderer",
")",
"\n",
"}"
] |
// Org is a convenience name for OrgOptions
|
[
"Org",
"is",
"a",
"convenience",
"name",
"for",
"OrgOptions"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/goorgeous.go#L49-L51
|
15,159 |
chaseadamsio/goorgeous
|
goorgeous.go
|
IsKeyword
|
func IsKeyword(data []byte) bool {
return len(data) > 2 && charMatches(data[0], '#') && charMatches(data[1], '+') && !charMatches(data[2], ' ')
}
|
go
|
func IsKeyword(data []byte) bool {
return len(data) > 2 && charMatches(data[0], '#') && charMatches(data[1], '+') && !charMatches(data[2], ' ')
}
|
[
"func",
"IsKeyword",
"(",
"data",
"[",
"]",
"byte",
")",
"bool",
"{",
"return",
"len",
"(",
"data",
")",
">",
"2",
"&&",
"charMatches",
"(",
"data",
"[",
"0",
"]",
",",
"'#'",
")",
"&&",
"charMatches",
"(",
"data",
"[",
"1",
"]",
",",
"'+'",
")",
"&&",
"!",
"charMatches",
"(",
"data",
"[",
"2",
"]",
",",
"' '",
")",
"\n",
"}"
] |
// Elements
// ~~ Keywords
|
[
"Elements",
"~~",
"Keywords"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/goorgeous.go#L543-L545
|
15,160 |
chaseadamsio/goorgeous
|
goorgeous.go
|
generateVerbatim
|
func generateVerbatim(p *parser, out *bytes.Buffer, data []byte, offset int) int {
return generator(p, out, data, offset, '=', false, p.r.CodeSpan)
}
|
go
|
func generateVerbatim(p *parser, out *bytes.Buffer, data []byte, offset int) int {
return generator(p, out, data, offset, '=', false, p.r.CodeSpan)
}
|
[
"func",
"generateVerbatim",
"(",
"p",
"*",
"parser",
",",
"out",
"*",
"bytes",
".",
"Buffer",
",",
"data",
"[",
"]",
"byte",
",",
"offset",
"int",
")",
"int",
"{",
"return",
"generator",
"(",
"p",
",",
"out",
",",
"data",
",",
"offset",
",",
"'='",
",",
"false",
",",
"p",
".",
"r",
".",
"CodeSpan",
")",
"\n",
"}"
] |
// ~~ Text Markup
|
[
"~~",
"Text",
"Markup"
] |
dcf1ef873b8987bf12596fe6951c48347986eb2f
|
https://github.com/chaseadamsio/goorgeous/blob/dcf1ef873b8987bf12596fe6951c48347986eb2f/goorgeous.go#L694-L696
|
15,161 |
basgys/goxml2json
|
plugins.go
|
AddToEncoder
|
func (tc *customTypeConverter) AddToEncoder(e *Encoder) *Encoder {
e.tc = tc
return e
}
|
go
|
func (tc *customTypeConverter) AddToEncoder(e *Encoder) *Encoder {
e.tc = tc
return e
}
|
[
"func",
"(",
"tc",
"*",
"customTypeConverter",
")",
"AddToEncoder",
"(",
"e",
"*",
"Encoder",
")",
"*",
"Encoder",
"{",
"e",
".",
"tc",
"=",
"tc",
"\n",
"return",
"e",
"\n",
"}"
] |
// Adds the type converter to the encoder
|
[
"Adds",
"the",
"type",
"converter",
"to",
"the",
"encoder"
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/plugins.go#L61-L64
|
15,162 |
basgys/goxml2json
|
encoder.go
|
Encode
|
func (enc *Encoder) Encode(root *Node) error {
if enc.err != nil {
return enc.err
}
if root == nil {
return nil
}
enc.err = enc.format(root, 0)
// Terminate each value with a newline.
// This makes the output look a little nicer
// when debugging, and some kind of space
// is required if the encoded value was a number,
// so that the reader knows there aren't more
// digits coming.
enc.write("\n")
return enc.err
}
|
go
|
func (enc *Encoder) Encode(root *Node) error {
if enc.err != nil {
return enc.err
}
if root == nil {
return nil
}
enc.err = enc.format(root, 0)
// Terminate each value with a newline.
// This makes the output look a little nicer
// when debugging, and some kind of space
// is required if the encoded value was a number,
// so that the reader knows there aren't more
// digits coming.
enc.write("\n")
return enc.err
}
|
[
"func",
"(",
"enc",
"*",
"Encoder",
")",
"Encode",
"(",
"root",
"*",
"Node",
")",
"error",
"{",
"if",
"enc",
".",
"err",
"!=",
"nil",
"{",
"return",
"enc",
".",
"err",
"\n",
"}",
"\n",
"if",
"root",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"enc",
".",
"err",
"=",
"enc",
".",
"format",
"(",
"root",
",",
"0",
")",
"\n\n",
"// Terminate each value with a newline.",
"// This makes the output look a little nicer",
"// when debugging, and some kind of space",
"// is required if the encoded value was a number,",
"// so that the reader knows there aren't more",
"// digits coming.",
"enc",
".",
"write",
"(",
"\"",
"\\n",
"\"",
")",
"\n\n",
"return",
"enc",
".",
"err",
"\n",
"}"
] |
// Encode writes the JSON encoding of v to the stream
|
[
"Encode",
"writes",
"the",
"JSON",
"encoding",
"of",
"v",
"to",
"the",
"stream"
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/encoder.go#L28-L47
|
15,163 |
basgys/goxml2json
|
jstype.go
|
Str2JSType
|
func Str2JSType(s string) JSType {
var (
output JSType
)
s = strings.TrimSpace(s) // santize the given string
switch {
case isBool(s):
output = Bool
case isFloat(s):
output = Float
case isInt(s):
output = Int
case isNull(s):
output = Null
default:
output = String // if all alternatives have been eliminated, the input is a string
}
return output
}
|
go
|
func Str2JSType(s string) JSType {
var (
output JSType
)
s = strings.TrimSpace(s) // santize the given string
switch {
case isBool(s):
output = Bool
case isFloat(s):
output = Float
case isInt(s):
output = Int
case isNull(s):
output = Null
default:
output = String // if all alternatives have been eliminated, the input is a string
}
return output
}
|
[
"func",
"Str2JSType",
"(",
"s",
"string",
")",
"JSType",
"{",
"var",
"(",
"output",
"JSType",
"\n",
")",
"\n",
"s",
"=",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
"// santize the given string",
"\n",
"switch",
"{",
"case",
"isBool",
"(",
"s",
")",
":",
"output",
"=",
"Bool",
"\n",
"case",
"isFloat",
"(",
"s",
")",
":",
"output",
"=",
"Float",
"\n",
"case",
"isInt",
"(",
"s",
")",
":",
"output",
"=",
"Int",
"\n",
"case",
"isNull",
"(",
"s",
")",
":",
"output",
"=",
"Null",
"\n",
"default",
":",
"output",
"=",
"String",
"// if all alternatives have been eliminated, the input is a string",
"\n",
"}",
"\n",
"return",
"output",
"\n",
"}"
] |
// Str2JSType extract a JavaScript type from a string
|
[
"Str2JSType",
"extract",
"a",
"JavaScript",
"type",
"from",
"a",
"string"
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/jstype.go#L21-L39
|
15,164 |
basgys/goxml2json
|
converter.go
|
Convert
|
func Convert(r io.Reader, ps ...plugin) (*bytes.Buffer, error) {
// Decode XML document
root := &Node{}
err := NewDecoder(r, ps...).Decode(root)
if err != nil {
return nil, err
}
// Then encode it in JSON
buf := new(bytes.Buffer)
e := NewEncoder(buf, ps...)
err = e.Encode(root)
if err != nil {
return nil, err
}
return buf, nil
}
|
go
|
func Convert(r io.Reader, ps ...plugin) (*bytes.Buffer, error) {
// Decode XML document
root := &Node{}
err := NewDecoder(r, ps...).Decode(root)
if err != nil {
return nil, err
}
// Then encode it in JSON
buf := new(bytes.Buffer)
e := NewEncoder(buf, ps...)
err = e.Encode(root)
if err != nil {
return nil, err
}
return buf, nil
}
|
[
"func",
"Convert",
"(",
"r",
"io",
".",
"Reader",
",",
"ps",
"...",
"plugin",
")",
"(",
"*",
"bytes",
".",
"Buffer",
",",
"error",
")",
"{",
"// Decode XML document",
"root",
":=",
"&",
"Node",
"{",
"}",
"\n",
"err",
":=",
"NewDecoder",
"(",
"r",
",",
"ps",
"...",
")",
".",
"Decode",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Then encode it in JSON",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"e",
":=",
"NewEncoder",
"(",
"buf",
",",
"ps",
"...",
")",
"\n",
"err",
"=",
"e",
".",
"Encode",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"buf",
",",
"nil",
"\n",
"}"
] |
// Convert converts the given XML document to JSON
|
[
"Convert",
"converts",
"the",
"given",
"XML",
"document",
"to",
"JSON"
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/converter.go#L9-L26
|
15,165 |
basgys/goxml2json
|
struct.go
|
AddChild
|
func (n *Node) AddChild(s string, c *Node) {
// Lazy lazy
if n.Children == nil {
n.Children = map[string]Nodes{}
}
n.Children[s] = append(n.Children[s], c)
}
|
go
|
func (n *Node) AddChild(s string, c *Node) {
// Lazy lazy
if n.Children == nil {
n.Children = map[string]Nodes{}
}
n.Children[s] = append(n.Children[s], c)
}
|
[
"func",
"(",
"n",
"*",
"Node",
")",
"AddChild",
"(",
"s",
"string",
",",
"c",
"*",
"Node",
")",
"{",
"// Lazy lazy",
"if",
"n",
".",
"Children",
"==",
"nil",
"{",
"n",
".",
"Children",
"=",
"map",
"[",
"string",
"]",
"Nodes",
"{",
"}",
"\n",
"}",
"\n\n",
"n",
".",
"Children",
"[",
"s",
"]",
"=",
"append",
"(",
"n",
".",
"Children",
"[",
"s",
"]",
",",
"c",
")",
"\n",
"}"
] |
// AddChild appends a node to the list of children
|
[
"AddChild",
"appends",
"a",
"node",
"to",
"the",
"list",
"of",
"children"
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/struct.go#L18-L25
|
15,166 |
basgys/goxml2json
|
struct.go
|
GetChild
|
func (n *Node) GetChild(path string) *Node {
result := n
names := strings.Split(path, ".")
for _, name := range names {
children, exists := result.Children[name]
if !exists {
return nil
}
if len(children) == 0 {
return nil
}
result = children[0]
}
return result
}
|
go
|
func (n *Node) GetChild(path string) *Node {
result := n
names := strings.Split(path, ".")
for _, name := range names {
children, exists := result.Children[name]
if !exists {
return nil
}
if len(children) == 0 {
return nil
}
result = children[0]
}
return result
}
|
[
"func",
"(",
"n",
"*",
"Node",
")",
"GetChild",
"(",
"path",
"string",
")",
"*",
"Node",
"{",
"result",
":=",
"n",
"\n",
"names",
":=",
"strings",
".",
"Split",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"children",
",",
"exists",
":=",
"result",
".",
"Children",
"[",
"name",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"children",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"result",
"=",
"children",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] |
// GetChild returns child by path if exists. Path looks like "grandparent.parent.child.grandchild"
|
[
"GetChild",
"returns",
"child",
"by",
"path",
"if",
"exists",
".",
"Path",
"looks",
"like",
"grandparent",
".",
"parent",
".",
"child",
".",
"grandchild"
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/struct.go#L33-L47
|
15,167 |
basgys/goxml2json
|
decoder.go
|
Decode
|
func (dec *Decoder) Decode(root *Node) error {
xmlDec := xml.NewDecoder(dec.r)
// That will convert the charset if the provided XML is non-UTF-8
xmlDec.CharsetReader = charset.NewReaderLabel
// Create first element from the root node
elem := &element{
parent: nil,
n: root,
}
for {
t, _ := xmlDec.Token()
if t == nil {
break
}
switch se := t.(type) {
case xml.StartElement:
// Build new a new current element and link it to its parent
elem = &element{
parent: elem,
n: &Node{},
label: se.Name.Local,
}
// Extract attributes as children
for _, a := range se.Attr {
if _, ok := dec.excludeAttrs[a.Name.Local]; ok {
continue
}
elem.n.AddChild(dec.attributePrefix+a.Name.Local, &Node{Data: a.Value})
}
case xml.CharData:
// Extract XML data (if any)
elem.n.Data = trimNonGraphic(string(xml.CharData(se)))
case xml.EndElement:
// And add it to its parent list
if elem.parent != nil {
elem.parent.n.AddChild(elem.label, elem.n)
}
// Then change the current element to its parent
elem = elem.parent
}
}
for _, formatter := range dec.formatters {
formatter.Format(root)
}
return nil
}
|
go
|
func (dec *Decoder) Decode(root *Node) error {
xmlDec := xml.NewDecoder(dec.r)
// That will convert the charset if the provided XML is non-UTF-8
xmlDec.CharsetReader = charset.NewReaderLabel
// Create first element from the root node
elem := &element{
parent: nil,
n: root,
}
for {
t, _ := xmlDec.Token()
if t == nil {
break
}
switch se := t.(type) {
case xml.StartElement:
// Build new a new current element and link it to its parent
elem = &element{
parent: elem,
n: &Node{},
label: se.Name.Local,
}
// Extract attributes as children
for _, a := range se.Attr {
if _, ok := dec.excludeAttrs[a.Name.Local]; ok {
continue
}
elem.n.AddChild(dec.attributePrefix+a.Name.Local, &Node{Data: a.Value})
}
case xml.CharData:
// Extract XML data (if any)
elem.n.Data = trimNonGraphic(string(xml.CharData(se)))
case xml.EndElement:
// And add it to its parent list
if elem.parent != nil {
elem.parent.n.AddChild(elem.label, elem.n)
}
// Then change the current element to its parent
elem = elem.parent
}
}
for _, formatter := range dec.formatters {
formatter.Format(root)
}
return nil
}
|
[
"func",
"(",
"dec",
"*",
"Decoder",
")",
"Decode",
"(",
"root",
"*",
"Node",
")",
"error",
"{",
"xmlDec",
":=",
"xml",
".",
"NewDecoder",
"(",
"dec",
".",
"r",
")",
"\n\n",
"// That will convert the charset if the provided XML is non-UTF-8",
"xmlDec",
".",
"CharsetReader",
"=",
"charset",
".",
"NewReaderLabel",
"\n\n",
"// Create first element from the root node",
"elem",
":=",
"&",
"element",
"{",
"parent",
":",
"nil",
",",
"n",
":",
"root",
",",
"}",
"\n\n",
"for",
"{",
"t",
",",
"_",
":=",
"xmlDec",
".",
"Token",
"(",
")",
"\n",
"if",
"t",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n\n",
"switch",
"se",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"xml",
".",
"StartElement",
":",
"// Build new a new current element and link it to its parent",
"elem",
"=",
"&",
"element",
"{",
"parent",
":",
"elem",
",",
"n",
":",
"&",
"Node",
"{",
"}",
",",
"label",
":",
"se",
".",
"Name",
".",
"Local",
",",
"}",
"\n\n",
"// Extract attributes as children",
"for",
"_",
",",
"a",
":=",
"range",
"se",
".",
"Attr",
"{",
"if",
"_",
",",
"ok",
":=",
"dec",
".",
"excludeAttrs",
"[",
"a",
".",
"Name",
".",
"Local",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"elem",
".",
"n",
".",
"AddChild",
"(",
"dec",
".",
"attributePrefix",
"+",
"a",
".",
"Name",
".",
"Local",
",",
"&",
"Node",
"{",
"Data",
":",
"a",
".",
"Value",
"}",
")",
"\n",
"}",
"\n",
"case",
"xml",
".",
"CharData",
":",
"// Extract XML data (if any)",
"elem",
".",
"n",
".",
"Data",
"=",
"trimNonGraphic",
"(",
"string",
"(",
"xml",
".",
"CharData",
"(",
"se",
")",
")",
")",
"\n",
"case",
"xml",
".",
"EndElement",
":",
"// And add it to its parent list",
"if",
"elem",
".",
"parent",
"!=",
"nil",
"{",
"elem",
".",
"parent",
".",
"n",
".",
"AddChild",
"(",
"elem",
".",
"label",
",",
"elem",
".",
"n",
")",
"\n",
"}",
"\n\n",
"// Then change the current element to its parent",
"elem",
"=",
"elem",
".",
"parent",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"formatter",
":=",
"range",
"dec",
".",
"formatters",
"{",
"formatter",
".",
"Format",
"(",
"root",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Decode reads the next JSON-encoded value from its
// input and stores it in the value pointed to by v.
|
[
"Decode",
"reads",
"the",
"next",
"JSON",
"-",
"encoded",
"value",
"from",
"its",
"input",
"and",
"stores",
"it",
"in",
"the",
"value",
"pointed",
"to",
"by",
"v",
"."
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/decoder.go#L67-L120
|
15,168 |
basgys/goxml2json
|
decoder.go
|
trimNonGraphic
|
func trimNonGraphic(s string) string {
if s == "" {
return s
}
var first *int
var last int
for i, r := range []rune(s) {
if !unicode.IsGraphic(r) || unicode.IsSpace(r) {
continue
}
if first == nil {
f := i // copy i
first = &f
last = i
} else {
last = i
}
}
// If first is nil, it means there are no graphic characters
if first == nil {
return ""
}
return string([]rune(s)[*first : last+1])
}
|
go
|
func trimNonGraphic(s string) string {
if s == "" {
return s
}
var first *int
var last int
for i, r := range []rune(s) {
if !unicode.IsGraphic(r) || unicode.IsSpace(r) {
continue
}
if first == nil {
f := i // copy i
first = &f
last = i
} else {
last = i
}
}
// If first is nil, it means there are no graphic characters
if first == nil {
return ""
}
return string([]rune(s)[*first : last+1])
}
|
[
"func",
"trimNonGraphic",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"s",
"\n",
"}",
"\n\n",
"var",
"first",
"*",
"int",
"\n",
"var",
"last",
"int",
"\n",
"for",
"i",
",",
"r",
":=",
"range",
"[",
"]",
"rune",
"(",
"s",
")",
"{",
"if",
"!",
"unicode",
".",
"IsGraphic",
"(",
"r",
")",
"||",
"unicode",
".",
"IsSpace",
"(",
"r",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"first",
"==",
"nil",
"{",
"f",
":=",
"i",
"// copy i",
"\n",
"first",
"=",
"&",
"f",
"\n",
"last",
"=",
"i",
"\n",
"}",
"else",
"{",
"last",
"=",
"i",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If first is nil, it means there are no graphic characters",
"if",
"first",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"[",
"]",
"rune",
"(",
"s",
")",
"[",
"*",
"first",
":",
"last",
"+",
"1",
"]",
")",
"\n",
"}"
] |
// trimNonGraphic returns a slice of the string s, with all leading and trailing
// non graphic characters and spaces removed.
//
// Graphic characters include letters, marks, numbers, punctuation, symbols,
// and spaces, from categories L, M, N, P, S, Zs.
// Spacing characters are set by category Z and property Pattern_White_Space.
|
[
"trimNonGraphic",
"returns",
"a",
"slice",
"of",
"the",
"string",
"s",
"with",
"all",
"leading",
"and",
"trailing",
"non",
"graphic",
"characters",
"and",
"spaces",
"removed",
".",
"Graphic",
"characters",
"include",
"letters",
"marks",
"numbers",
"punctuation",
"symbols",
"and",
"spaces",
"from",
"categories",
"L",
"M",
"N",
"P",
"S",
"Zs",
".",
"Spacing",
"characters",
"are",
"set",
"by",
"category",
"Z",
"and",
"property",
"Pattern_White_Space",
"."
] |
996d9fc8d3135d0ac85060984a7bef857e7db738
|
https://github.com/basgys/goxml2json/blob/996d9fc8d3135d0ac85060984a7bef857e7db738/decoder.go#L128-L155
|
15,169 |
antonholmquist/jason
|
jason.go
|
Null
|
func (v *Value) Null() error {
var valid bool
// Check the type of this data
switch v.data.(type) {
case nil:
valid = v.exists // Valid only if j also exists, since other values could possibly also be nil
break
}
if valid {
return nil
}
return ErrNotNull
}
|
go
|
func (v *Value) Null() error {
var valid bool
// Check the type of this data
switch v.data.(type) {
case nil:
valid = v.exists // Valid only if j also exists, since other values could possibly also be nil
break
}
if valid {
return nil
}
return ErrNotNull
}
|
[
"func",
"(",
"v",
"*",
"Value",
")",
"Null",
"(",
")",
"error",
"{",
"var",
"valid",
"bool",
"\n\n",
"// Check the type of this data",
"switch",
"v",
".",
"data",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"valid",
"=",
"v",
".",
"exists",
"// Valid only if j also exists, since other values could possibly also be nil",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"valid",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"ErrNotNull",
"\n\n",
"}"
] |
// Returns an error if the value is not actually null
|
[
"Returns",
"an",
"error",
"if",
"the",
"value",
"is",
"not",
"actually",
"null"
] |
426ade25b261bcb4a7ad58c65badfc731854e92b
|
https://github.com/antonholmquist/jason/blob/426ade25b261bcb4a7ad58c65badfc731854e92b/jason.go#L608-L624
|
15,170 |
lunixbochs/struc
|
legacy.go
|
PackWithOrder
|
func PackWithOrder(w io.Writer, data interface{}, order binary.ByteOrder) error {
return PackWithOptions(w, data, &Options{Order: order})
}
|
go
|
func PackWithOrder(w io.Writer, data interface{}, order binary.ByteOrder) error {
return PackWithOptions(w, data, &Options{Order: order})
}
|
[
"func",
"PackWithOrder",
"(",
"w",
"io",
".",
"Writer",
",",
"data",
"interface",
"{",
"}",
",",
"order",
"binary",
".",
"ByteOrder",
")",
"error",
"{",
"return",
"PackWithOptions",
"(",
"w",
",",
"data",
",",
"&",
"Options",
"{",
"Order",
":",
"order",
"}",
")",
"\n",
"}"
] |
// Deprecated. Use PackWithOptions.
|
[
"Deprecated",
".",
"Use",
"PackWithOptions",
"."
] |
a9e4041416c2cd121670f6c3be4b0d523ee49b8a
|
https://github.com/lunixbochs/struc/blob/a9e4041416c2cd121670f6c3be4b0d523ee49b8a/legacy.go#L9-L11
|
15,171 |
lunixbochs/struc
|
legacy.go
|
UnpackWithOrder
|
func UnpackWithOrder(r io.Reader, data interface{}, order binary.ByteOrder) error {
return UnpackWithOptions(r, data, &Options{Order: order})
}
|
go
|
func UnpackWithOrder(r io.Reader, data interface{}, order binary.ByteOrder) error {
return UnpackWithOptions(r, data, &Options{Order: order})
}
|
[
"func",
"UnpackWithOrder",
"(",
"r",
"io",
".",
"Reader",
",",
"data",
"interface",
"{",
"}",
",",
"order",
"binary",
".",
"ByteOrder",
")",
"error",
"{",
"return",
"UnpackWithOptions",
"(",
"r",
",",
"data",
",",
"&",
"Options",
"{",
"Order",
":",
"order",
"}",
")",
"\n",
"}"
] |
// Deprecated. Use UnpackWithOptions.
|
[
"Deprecated",
".",
"Use",
"UnpackWithOptions",
"."
] |
a9e4041416c2cd121670f6c3be4b0d523ee49b8a
|
https://github.com/lunixbochs/struc/blob/a9e4041416c2cd121670f6c3be4b0d523ee49b8a/legacy.go#L14-L16
|
15,172 |
axiomhq/hyperloglog
|
hyperloglog.go
|
new
|
func new(precision uint8, sparse bool) (*Sketch, error) {
if precision < 4 || precision > 18 {
return nil, fmt.Errorf("p has to be >= 4 and <= 18")
}
m := uint32(math.Pow(2, float64(precision)))
s := &Sketch{
m: m,
p: precision,
alpha: alpha(float64(m)),
}
if sparse {
s.sparse = true
s.tmpSet = set{}
s.sparseList = newCompressedList(int(m))
} else {
s.regs = newRegisters(m)
}
return s, nil
}
|
go
|
func new(precision uint8, sparse bool) (*Sketch, error) {
if precision < 4 || precision > 18 {
return nil, fmt.Errorf("p has to be >= 4 and <= 18")
}
m := uint32(math.Pow(2, float64(precision)))
s := &Sketch{
m: m,
p: precision,
alpha: alpha(float64(m)),
}
if sparse {
s.sparse = true
s.tmpSet = set{}
s.sparseList = newCompressedList(int(m))
} else {
s.regs = newRegisters(m)
}
return s, nil
}
|
[
"func",
"new",
"(",
"precision",
"uint8",
",",
"sparse",
"bool",
")",
"(",
"*",
"Sketch",
",",
"error",
")",
"{",
"if",
"precision",
"<",
"4",
"||",
"precision",
">",
"18",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"m",
":=",
"uint32",
"(",
"math",
".",
"Pow",
"(",
"2",
",",
"float64",
"(",
"precision",
")",
")",
")",
"\n",
"s",
":=",
"&",
"Sketch",
"{",
"m",
":",
"m",
",",
"p",
":",
"precision",
",",
"alpha",
":",
"alpha",
"(",
"float64",
"(",
"m",
")",
")",
",",
"}",
"\n",
"if",
"sparse",
"{",
"s",
".",
"sparse",
"=",
"true",
"\n",
"s",
".",
"tmpSet",
"=",
"set",
"{",
"}",
"\n",
"s",
".",
"sparseList",
"=",
"newCompressedList",
"(",
"int",
"(",
"m",
")",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"regs",
"=",
"newRegisters",
"(",
"m",
")",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] |
// new returns a HyperLogLog Sketch with 2^precision registers
|
[
"new",
"returns",
"a",
"HyperLogLog",
"Sketch",
"with",
"2^precision",
"registers"
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L63-L81
|
15,173 |
axiomhq/hyperloglog
|
hyperloglog.go
|
Clone
|
func (sk *Sketch) Clone() *Sketch {
return &Sketch{
b: sk.b,
p: sk.p,
m: sk.m,
alpha: sk.alpha,
sparse: sk.sparse,
tmpSet: sk.tmpSet.Clone(),
sparseList: sk.sparseList.Clone(),
regs: sk.regs.clone(),
}
}
|
go
|
func (sk *Sketch) Clone() *Sketch {
return &Sketch{
b: sk.b,
p: sk.p,
m: sk.m,
alpha: sk.alpha,
sparse: sk.sparse,
tmpSet: sk.tmpSet.Clone(),
sparseList: sk.sparseList.Clone(),
regs: sk.regs.clone(),
}
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"Clone",
"(",
")",
"*",
"Sketch",
"{",
"return",
"&",
"Sketch",
"{",
"b",
":",
"sk",
".",
"b",
",",
"p",
":",
"sk",
".",
"p",
",",
"m",
":",
"sk",
".",
"m",
",",
"alpha",
":",
"sk",
".",
"alpha",
",",
"sparse",
":",
"sk",
".",
"sparse",
",",
"tmpSet",
":",
"sk",
".",
"tmpSet",
".",
"Clone",
"(",
")",
",",
"sparseList",
":",
"sk",
".",
"sparseList",
".",
"Clone",
"(",
")",
",",
"regs",
":",
"sk",
".",
"regs",
".",
"clone",
"(",
")",
",",
"}",
"\n",
"}"
] |
// Clone returns a deep copy of sk.
|
[
"Clone",
"returns",
"a",
"deep",
"copy",
"of",
"sk",
"."
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L84-L95
|
15,174 |
axiomhq/hyperloglog
|
hyperloglog.go
|
maybeToNormal
|
func (sk *Sketch) maybeToNormal() {
if uint32(len(sk.tmpSet))*100 > sk.m {
sk.mergeSparse()
if uint32(sk.sparseList.Len()) > sk.m {
sk.toNormal()
}
}
}
|
go
|
func (sk *Sketch) maybeToNormal() {
if uint32(len(sk.tmpSet))*100 > sk.m {
sk.mergeSparse()
if uint32(sk.sparseList.Len()) > sk.m {
sk.toNormal()
}
}
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"maybeToNormal",
"(",
")",
"{",
"if",
"uint32",
"(",
"len",
"(",
"sk",
".",
"tmpSet",
")",
")",
"*",
"100",
">",
"sk",
".",
"m",
"{",
"sk",
".",
"mergeSparse",
"(",
")",
"\n",
"if",
"uint32",
"(",
"sk",
".",
"sparseList",
".",
"Len",
"(",
")",
")",
">",
"sk",
".",
"m",
"{",
"sk",
".",
"toNormal",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Converts to normal if the sparse list is too large.
|
[
"Converts",
"to",
"normal",
"if",
"the",
"sparse",
"list",
"is",
"too",
"large",
"."
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L98-L105
|
15,175 |
axiomhq/hyperloglog
|
hyperloglog.go
|
Merge
|
func (sk *Sketch) Merge(other *Sketch) error {
if other == nil {
// Nothing to do
return nil
}
cpOther := other.Clone()
if sk.p != cpOther.p {
return errors.New("precisions must be equal")
}
if sk.sparse && other.sparse {
for k := range other.tmpSet {
sk.tmpSet.add(k)
}
for iter := other.sparseList.Iter(); iter.HasNext(); {
sk.tmpSet.add(iter.Next())
}
sk.maybeToNormal()
return nil
}
if sk.sparse {
sk.toNormal()
}
if cpOther.sparse {
for k := range cpOther.tmpSet {
i, r := decodeHash(k, cpOther.p, pp)
sk.insert(i, r)
}
for iter := cpOther.sparseList.Iter(); iter.HasNext(); {
i, r := decodeHash(iter.Next(), cpOther.p, pp)
sk.insert(i, r)
}
} else {
if sk.b < cpOther.b {
sk.regs.rebase(cpOther.b - sk.b)
sk.b = cpOther.b
} else {
cpOther.regs.rebase(sk.b - cpOther.b)
cpOther.b = sk.b
}
for i, v := range cpOther.regs.tailcuts {
v1 := v.get(0)
if v1 > sk.regs.get(uint32(i)*2) {
sk.regs.set(uint32(i)*2, v1)
}
v2 := v.get(1)
if v2 > sk.regs.get(1+uint32(i)*2) {
sk.regs.set(1+uint32(i)*2, v2)
}
}
}
return nil
}
|
go
|
func (sk *Sketch) Merge(other *Sketch) error {
if other == nil {
// Nothing to do
return nil
}
cpOther := other.Clone()
if sk.p != cpOther.p {
return errors.New("precisions must be equal")
}
if sk.sparse && other.sparse {
for k := range other.tmpSet {
sk.tmpSet.add(k)
}
for iter := other.sparseList.Iter(); iter.HasNext(); {
sk.tmpSet.add(iter.Next())
}
sk.maybeToNormal()
return nil
}
if sk.sparse {
sk.toNormal()
}
if cpOther.sparse {
for k := range cpOther.tmpSet {
i, r := decodeHash(k, cpOther.p, pp)
sk.insert(i, r)
}
for iter := cpOther.sparseList.Iter(); iter.HasNext(); {
i, r := decodeHash(iter.Next(), cpOther.p, pp)
sk.insert(i, r)
}
} else {
if sk.b < cpOther.b {
sk.regs.rebase(cpOther.b - sk.b)
sk.b = cpOther.b
} else {
cpOther.regs.rebase(sk.b - cpOther.b)
cpOther.b = sk.b
}
for i, v := range cpOther.regs.tailcuts {
v1 := v.get(0)
if v1 > sk.regs.get(uint32(i)*2) {
sk.regs.set(uint32(i)*2, v1)
}
v2 := v.get(1)
if v2 > sk.regs.get(1+uint32(i)*2) {
sk.regs.set(1+uint32(i)*2, v2)
}
}
}
return nil
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"Merge",
"(",
"other",
"*",
"Sketch",
")",
"error",
"{",
"if",
"other",
"==",
"nil",
"{",
"// Nothing to do",
"return",
"nil",
"\n",
"}",
"\n",
"cpOther",
":=",
"other",
".",
"Clone",
"(",
")",
"\n\n",
"if",
"sk",
".",
"p",
"!=",
"cpOther",
".",
"p",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"sk",
".",
"sparse",
"&&",
"other",
".",
"sparse",
"{",
"for",
"k",
":=",
"range",
"other",
".",
"tmpSet",
"{",
"sk",
".",
"tmpSet",
".",
"add",
"(",
"k",
")",
"\n",
"}",
"\n",
"for",
"iter",
":=",
"other",
".",
"sparseList",
".",
"Iter",
"(",
")",
";",
"iter",
".",
"HasNext",
"(",
")",
";",
"{",
"sk",
".",
"tmpSet",
".",
"add",
"(",
"iter",
".",
"Next",
"(",
")",
")",
"\n",
"}",
"\n",
"sk",
".",
"maybeToNormal",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"sk",
".",
"sparse",
"{",
"sk",
".",
"toNormal",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"cpOther",
".",
"sparse",
"{",
"for",
"k",
":=",
"range",
"cpOther",
".",
"tmpSet",
"{",
"i",
",",
"r",
":=",
"decodeHash",
"(",
"k",
",",
"cpOther",
".",
"p",
",",
"pp",
")",
"\n",
"sk",
".",
"insert",
"(",
"i",
",",
"r",
")",
"\n",
"}",
"\n\n",
"for",
"iter",
":=",
"cpOther",
".",
"sparseList",
".",
"Iter",
"(",
")",
";",
"iter",
".",
"HasNext",
"(",
")",
";",
"{",
"i",
",",
"r",
":=",
"decodeHash",
"(",
"iter",
".",
"Next",
"(",
")",
",",
"cpOther",
".",
"p",
",",
"pp",
")",
"\n",
"sk",
".",
"insert",
"(",
"i",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"sk",
".",
"b",
"<",
"cpOther",
".",
"b",
"{",
"sk",
".",
"regs",
".",
"rebase",
"(",
"cpOther",
".",
"b",
"-",
"sk",
".",
"b",
")",
"\n",
"sk",
".",
"b",
"=",
"cpOther",
".",
"b",
"\n",
"}",
"else",
"{",
"cpOther",
".",
"regs",
".",
"rebase",
"(",
"sk",
".",
"b",
"-",
"cpOther",
".",
"b",
")",
"\n",
"cpOther",
".",
"b",
"=",
"sk",
".",
"b",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"v",
":=",
"range",
"cpOther",
".",
"regs",
".",
"tailcuts",
"{",
"v1",
":=",
"v",
".",
"get",
"(",
"0",
")",
"\n",
"if",
"v1",
">",
"sk",
".",
"regs",
".",
"get",
"(",
"uint32",
"(",
"i",
")",
"*",
"2",
")",
"{",
"sk",
".",
"regs",
".",
"set",
"(",
"uint32",
"(",
"i",
")",
"*",
"2",
",",
"v1",
")",
"\n",
"}",
"\n",
"v2",
":=",
"v",
".",
"get",
"(",
"1",
")",
"\n",
"if",
"v2",
">",
"sk",
".",
"regs",
".",
"get",
"(",
"1",
"+",
"uint32",
"(",
"i",
")",
"*",
"2",
")",
"{",
"sk",
".",
"regs",
".",
"set",
"(",
"1",
"+",
"uint32",
"(",
"i",
")",
"*",
"2",
",",
"v2",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Merge takes another Sketch and combines it with Sketch h.
// If Sketch h is using the sparse Sketch, it will be converted
// to the normal Sketch.
|
[
"Merge",
"takes",
"another",
"Sketch",
"and",
"combines",
"it",
"with",
"Sketch",
"h",
".",
"If",
"Sketch",
"h",
"is",
"using",
"the",
"sparse",
"Sketch",
"it",
"will",
"be",
"converted",
"to",
"the",
"normal",
"Sketch",
"."
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L110-L167
|
15,176 |
axiomhq/hyperloglog
|
hyperloglog.go
|
toNormal
|
func (sk *Sketch) toNormal() {
if len(sk.tmpSet) > 0 {
sk.mergeSparse()
}
sk.regs = newRegisters(sk.m)
for iter := sk.sparseList.Iter(); iter.HasNext(); {
i, r := decodeHash(iter.Next(), sk.p, pp)
sk.insert(i, r)
}
sk.sparse = false
sk.tmpSet = nil
sk.sparseList = nil
}
|
go
|
func (sk *Sketch) toNormal() {
if len(sk.tmpSet) > 0 {
sk.mergeSparse()
}
sk.regs = newRegisters(sk.m)
for iter := sk.sparseList.Iter(); iter.HasNext(); {
i, r := decodeHash(iter.Next(), sk.p, pp)
sk.insert(i, r)
}
sk.sparse = false
sk.tmpSet = nil
sk.sparseList = nil
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"toNormal",
"(",
")",
"{",
"if",
"len",
"(",
"sk",
".",
"tmpSet",
")",
">",
"0",
"{",
"sk",
".",
"mergeSparse",
"(",
")",
"\n",
"}",
"\n\n",
"sk",
".",
"regs",
"=",
"newRegisters",
"(",
"sk",
".",
"m",
")",
"\n",
"for",
"iter",
":=",
"sk",
".",
"sparseList",
".",
"Iter",
"(",
")",
";",
"iter",
".",
"HasNext",
"(",
")",
";",
"{",
"i",
",",
"r",
":=",
"decodeHash",
"(",
"iter",
".",
"Next",
"(",
")",
",",
"sk",
".",
"p",
",",
"pp",
")",
"\n",
"sk",
".",
"insert",
"(",
"i",
",",
"r",
")",
"\n",
"}",
"\n\n",
"sk",
".",
"sparse",
"=",
"false",
"\n",
"sk",
".",
"tmpSet",
"=",
"nil",
"\n",
"sk",
".",
"sparseList",
"=",
"nil",
"\n",
"}"
] |
// Convert from sparse Sketch to dense Sketch.
|
[
"Convert",
"from",
"sparse",
"Sketch",
"to",
"dense",
"Sketch",
"."
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L170-L184
|
15,177 |
axiomhq/hyperloglog
|
hyperloglog.go
|
Insert
|
func (sk *Sketch) Insert(e []byte) bool {
x := hash(e)
return sk.InsertHash(x)
}
|
go
|
func (sk *Sketch) Insert(e []byte) bool {
x := hash(e)
return sk.InsertHash(x)
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"Insert",
"(",
"e",
"[",
"]",
"byte",
")",
"bool",
"{",
"x",
":=",
"hash",
"(",
"e",
")",
"\n",
"return",
"sk",
".",
"InsertHash",
"(",
"x",
")",
"\n",
"}"
] |
// Insert adds element e to sketch
|
[
"Insert",
"adds",
"element",
"e",
"to",
"sketch"
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L212-L215
|
15,178 |
axiomhq/hyperloglog
|
hyperloglog.go
|
InsertHash
|
func (sk *Sketch) InsertHash(x uint64) bool {
if sk.sparse {
changed := sk.tmpSet.add(encodeHash(x, sk.p, pp))
if !changed {
return false
}
if uint32(len(sk.tmpSet))*100 > sk.m/2 {
sk.mergeSparse()
if uint32(sk.sparseList.Len()) > sk.m/2 {
sk.toNormal()
}
}
return true
} else {
i, r := getPosVal(x, sk.p)
return sk.insert(uint32(i), r)
}
}
|
go
|
func (sk *Sketch) InsertHash(x uint64) bool {
if sk.sparse {
changed := sk.tmpSet.add(encodeHash(x, sk.p, pp))
if !changed {
return false
}
if uint32(len(sk.tmpSet))*100 > sk.m/2 {
sk.mergeSparse()
if uint32(sk.sparseList.Len()) > sk.m/2 {
sk.toNormal()
}
}
return true
} else {
i, r := getPosVal(x, sk.p)
return sk.insert(uint32(i), r)
}
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"InsertHash",
"(",
"x",
"uint64",
")",
"bool",
"{",
"if",
"sk",
".",
"sparse",
"{",
"changed",
":=",
"sk",
".",
"tmpSet",
".",
"add",
"(",
"encodeHash",
"(",
"x",
",",
"sk",
".",
"p",
",",
"pp",
")",
")",
"\n",
"if",
"!",
"changed",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"uint32",
"(",
"len",
"(",
"sk",
".",
"tmpSet",
")",
")",
"*",
"100",
">",
"sk",
".",
"m",
"/",
"2",
"{",
"sk",
".",
"mergeSparse",
"(",
")",
"\n",
"if",
"uint32",
"(",
"sk",
".",
"sparseList",
".",
"Len",
"(",
")",
")",
">",
"sk",
".",
"m",
"/",
"2",
"{",
"sk",
".",
"toNormal",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"else",
"{",
"i",
",",
"r",
":=",
"getPosVal",
"(",
"x",
",",
"sk",
".",
"p",
")",
"\n",
"return",
"sk",
".",
"insert",
"(",
"uint32",
"(",
"i",
")",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// InsertHash adds hash x to sketch
|
[
"InsertHash",
"adds",
"hash",
"x",
"to",
"sketch"
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L218-L235
|
15,179 |
axiomhq/hyperloglog
|
hyperloglog.go
|
Estimate
|
func (sk *Sketch) Estimate() uint64 {
if sk.sparse {
sk.mergeSparse()
return uint64(linearCount(mp, mp-sk.sparseList.count))
}
sum, ez := sk.regs.sumAndZeros(sk.b)
m := float64(sk.m)
var est float64
var beta func(float64) float64
if sk.p < 16 {
beta = beta14
} else {
beta = beta16
}
if sk.b == 0 {
est = (sk.alpha * m * (m - ez) / (sum + beta(ez)))
} else {
est = (sk.alpha * m * m / sum)
}
return uint64(est + 0.5)
}
|
go
|
func (sk *Sketch) Estimate() uint64 {
if sk.sparse {
sk.mergeSparse()
return uint64(linearCount(mp, mp-sk.sparseList.count))
}
sum, ez := sk.regs.sumAndZeros(sk.b)
m := float64(sk.m)
var est float64
var beta func(float64) float64
if sk.p < 16 {
beta = beta14
} else {
beta = beta16
}
if sk.b == 0 {
est = (sk.alpha * m * (m - ez) / (sum + beta(ez)))
} else {
est = (sk.alpha * m * m / sum)
}
return uint64(est + 0.5)
}
|
[
"func",
"(",
"sk",
"*",
"Sketch",
")",
"Estimate",
"(",
")",
"uint64",
"{",
"if",
"sk",
".",
"sparse",
"{",
"sk",
".",
"mergeSparse",
"(",
")",
"\n",
"return",
"uint64",
"(",
"linearCount",
"(",
"mp",
",",
"mp",
"-",
"sk",
".",
"sparseList",
".",
"count",
")",
")",
"\n",
"}",
"\n\n",
"sum",
",",
"ez",
":=",
"sk",
".",
"regs",
".",
"sumAndZeros",
"(",
"sk",
".",
"b",
")",
"\n",
"m",
":=",
"float64",
"(",
"sk",
".",
"m",
")",
"\n",
"var",
"est",
"float64",
"\n\n",
"var",
"beta",
"func",
"(",
"float64",
")",
"float64",
"\n",
"if",
"sk",
".",
"p",
"<",
"16",
"{",
"beta",
"=",
"beta14",
"\n",
"}",
"else",
"{",
"beta",
"=",
"beta16",
"\n",
"}",
"\n\n",
"if",
"sk",
".",
"b",
"==",
"0",
"{",
"est",
"=",
"(",
"sk",
".",
"alpha",
"*",
"m",
"*",
"(",
"m",
"-",
"ez",
")",
"/",
"(",
"sum",
"+",
"beta",
"(",
"ez",
")",
")",
")",
"\n",
"}",
"else",
"{",
"est",
"=",
"(",
"sk",
".",
"alpha",
"*",
"m",
"*",
"m",
"/",
"sum",
")",
"\n",
"}",
"\n\n",
"return",
"uint64",
"(",
"est",
"+",
"0.5",
")",
"\n",
"}"
] |
// Estimate returns the cardinality of the Sketch
|
[
"Estimate",
"returns",
"the",
"cardinality",
"of",
"the",
"Sketch"
] |
6335aff4f64ca1429ad8336540d3c3c97d63fdb1
|
https://github.com/axiomhq/hyperloglog/blob/6335aff4f64ca1429ad8336540d3c3c97d63fdb1/hyperloglog.go#L238-L262
|
15,180 |
chai2010/webp
|
image.go
|
AsMemPImage
|
func AsMemPImage(m interface{}) (p *MemPImage, ok bool) {
if m, ok := m.(*MemPImage); ok {
return m, true
}
if m, ok := m.(MemP); ok {
return &MemPImage{
XMemPMagic: MemPMagic,
XRect: m.Bounds(),
XChannels: m.Channels(),
XDataType: m.DataType(),
XPix: m.Pix(),
XStride: m.Stride(),
}, true
}
if m, ok := m.(*image.Gray); ok {
return &MemPImage{
XMemPMagic: MemPMagic,
XRect: m.Bounds(),
XChannels: 1,
XDataType: reflect.Uint8,
XPix: m.Pix,
XStride: m.Stride,
}, true
}
if m, ok := m.(*image.RGBA); ok {
return &MemPImage{
XMemPMagic: MemPMagic,
XRect: m.Bounds(),
XChannels: 4,
XDataType: reflect.Uint8,
XPix: m.Pix,
XStride: m.Stride,
}, true
}
return nil, false
}
|
go
|
func AsMemPImage(m interface{}) (p *MemPImage, ok bool) {
if m, ok := m.(*MemPImage); ok {
return m, true
}
if m, ok := m.(MemP); ok {
return &MemPImage{
XMemPMagic: MemPMagic,
XRect: m.Bounds(),
XChannels: m.Channels(),
XDataType: m.DataType(),
XPix: m.Pix(),
XStride: m.Stride(),
}, true
}
if m, ok := m.(*image.Gray); ok {
return &MemPImage{
XMemPMagic: MemPMagic,
XRect: m.Bounds(),
XChannels: 1,
XDataType: reflect.Uint8,
XPix: m.Pix,
XStride: m.Stride,
}, true
}
if m, ok := m.(*image.RGBA); ok {
return &MemPImage{
XMemPMagic: MemPMagic,
XRect: m.Bounds(),
XChannels: 4,
XDataType: reflect.Uint8,
XPix: m.Pix,
XStride: m.Stride,
}, true
}
return nil, false
}
|
[
"func",
"AsMemPImage",
"(",
"m",
"interface",
"{",
"}",
")",
"(",
"p",
"*",
"MemPImage",
",",
"ok",
"bool",
")",
"{",
"if",
"m",
",",
"ok",
":=",
"m",
".",
"(",
"*",
"MemPImage",
")",
";",
"ok",
"{",
"return",
"m",
",",
"true",
"\n",
"}",
"\n",
"if",
"m",
",",
"ok",
":=",
"m",
".",
"(",
"MemP",
")",
";",
"ok",
"{",
"return",
"&",
"MemPImage",
"{",
"XMemPMagic",
":",
"MemPMagic",
",",
"XRect",
":",
"m",
".",
"Bounds",
"(",
")",
",",
"XChannels",
":",
"m",
".",
"Channels",
"(",
")",
",",
"XDataType",
":",
"m",
".",
"DataType",
"(",
")",
",",
"XPix",
":",
"m",
".",
"Pix",
"(",
")",
",",
"XStride",
":",
"m",
".",
"Stride",
"(",
")",
",",
"}",
",",
"true",
"\n",
"}",
"\n",
"if",
"m",
",",
"ok",
":=",
"m",
".",
"(",
"*",
"image",
".",
"Gray",
")",
";",
"ok",
"{",
"return",
"&",
"MemPImage",
"{",
"XMemPMagic",
":",
"MemPMagic",
",",
"XRect",
":",
"m",
".",
"Bounds",
"(",
")",
",",
"XChannels",
":",
"1",
",",
"XDataType",
":",
"reflect",
".",
"Uint8",
",",
"XPix",
":",
"m",
".",
"Pix",
",",
"XStride",
":",
"m",
".",
"Stride",
",",
"}",
",",
"true",
"\n",
"}",
"\n",
"if",
"m",
",",
"ok",
":=",
"m",
".",
"(",
"*",
"image",
".",
"RGBA",
")",
";",
"ok",
"{",
"return",
"&",
"MemPImage",
"{",
"XMemPMagic",
":",
"MemPMagic",
",",
"XRect",
":",
"m",
".",
"Bounds",
"(",
")",
",",
"XChannels",
":",
"4",
",",
"XDataType",
":",
"reflect",
".",
"Uint8",
",",
"XPix",
":",
"m",
".",
"Pix",
",",
"XStride",
":",
"m",
".",
"Stride",
",",
"}",
",",
"true",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] |
// m is MemP or image.Image
|
[
"m",
"is",
"MemP",
"or",
"image",
".",
"Image"
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/image.go#L66-L101
|
15,181 |
chai2010/webp
|
rgb.go
|
NewRGBImage
|
func NewRGBImage(r image.Rectangle) *RGBImage {
w, h := r.Dx(), r.Dy()
pix := make([]uint8, 3*w*h)
return &RGBImage{
XPix: pix,
XStride: 3 * w,
XRect: r,
}
}
|
go
|
func NewRGBImage(r image.Rectangle) *RGBImage {
w, h := r.Dx(), r.Dy()
pix := make([]uint8, 3*w*h)
return &RGBImage{
XPix: pix,
XStride: 3 * w,
XRect: r,
}
}
|
[
"func",
"NewRGBImage",
"(",
"r",
"image",
".",
"Rectangle",
")",
"*",
"RGBImage",
"{",
"w",
",",
"h",
":=",
"r",
".",
"Dx",
"(",
")",
",",
"r",
".",
"Dy",
"(",
")",
"\n",
"pix",
":=",
"make",
"(",
"[",
"]",
"uint8",
",",
"3",
"*",
"w",
"*",
"h",
")",
"\n",
"return",
"&",
"RGBImage",
"{",
"XPix",
":",
"pix",
",",
"XStride",
":",
"3",
"*",
"w",
",",
"XRect",
":",
"r",
",",
"}",
"\n",
"}"
] |
// NewRGBImage returns a new RGBImage with the given bounds.
|
[
"NewRGBImage",
"returns",
"a",
"new",
"RGBImage",
"with",
"the",
"given",
"bounds",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/rgb.go#L128-L136
|
15,182 |
chai2010/webp
|
rgb48.go
|
NewRGB48Image
|
func NewRGB48Image(r image.Rectangle) *RGB48Image {
w, h := r.Dx(), r.Dy()
pix := make([]uint8, 6*w*h)
return &RGB48Image{
XPix: pix,
XStride: 6 * w,
XRect: r,
}
}
|
go
|
func NewRGB48Image(r image.Rectangle) *RGB48Image {
w, h := r.Dx(), r.Dy()
pix := make([]uint8, 6*w*h)
return &RGB48Image{
XPix: pix,
XStride: 6 * w,
XRect: r,
}
}
|
[
"func",
"NewRGB48Image",
"(",
"r",
"image",
".",
"Rectangle",
")",
"*",
"RGB48Image",
"{",
"w",
",",
"h",
":=",
"r",
".",
"Dx",
"(",
")",
",",
"r",
".",
"Dy",
"(",
")",
"\n",
"pix",
":=",
"make",
"(",
"[",
"]",
"uint8",
",",
"6",
"*",
"w",
"*",
"h",
")",
"\n",
"return",
"&",
"RGB48Image",
"{",
"XPix",
":",
"pix",
",",
"XStride",
":",
"6",
"*",
"w",
",",
"XRect",
":",
"r",
",",
"}",
"\n",
"}"
] |
// NewRGB48Image returns a new RGB48Image with the given bounds.
|
[
"NewRGB48Image",
"returns",
"a",
"new",
"RGB48Image",
"with",
"the",
"given",
"bounds",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/rgb48.go#L169-L177
|
15,183 |
chai2010/webp
|
reader.go
|
DecodeConfig
|
func DecodeConfig(r io.Reader) (config image.Config, err error) {
header := make([]byte, maxWebpHeaderSize)
n, err := r.Read(header)
if err != nil && err != io.EOF {
return
}
header, err = header[:n], nil
width, height, _, err := GetInfo(header)
if err != nil {
return
}
config.Width = width
config.Height = height
config.ColorModel = color.RGBAModel
return
}
|
go
|
func DecodeConfig(r io.Reader) (config image.Config, err error) {
header := make([]byte, maxWebpHeaderSize)
n, err := r.Read(header)
if err != nil && err != io.EOF {
return
}
header, err = header[:n], nil
width, height, _, err := GetInfo(header)
if err != nil {
return
}
config.Width = width
config.Height = height
config.ColorModel = color.RGBAModel
return
}
|
[
"func",
"DecodeConfig",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"config",
"image",
".",
"Config",
",",
"err",
"error",
")",
"{",
"header",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"maxWebpHeaderSize",
")",
"\n",
"n",
",",
"err",
":=",
"r",
".",
"Read",
"(",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"{",
"return",
"\n",
"}",
"\n",
"header",
",",
"err",
"=",
"header",
"[",
":",
"n",
"]",
",",
"nil",
"\n",
"width",
",",
"height",
",",
"_",
",",
"err",
":=",
"GetInfo",
"(",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"config",
".",
"Width",
"=",
"width",
"\n",
"config",
".",
"Height",
"=",
"height",
"\n",
"config",
".",
"ColorModel",
"=",
"color",
".",
"RGBAModel",
"\n",
"return",
"\n",
"}"
] |
// DecodeConfig returns the color model and dimensions of a WEBP image without
// decoding the entire image.
|
[
"DecodeConfig",
"returns",
"the",
"color",
"model",
"and",
"dimensions",
"of",
"a",
"WEBP",
"image",
"without",
"decoding",
"the",
"entire",
"image",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/reader.go#L69-L84
|
15,184 |
chai2010/webp
|
reader.go
|
Decode
|
func Decode(r io.Reader) (m image.Image, err error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return
}
if m, err = DecodeRGBA(data); err != nil {
return
}
return
}
|
go
|
func Decode(r io.Reader) (m image.Image, err error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return
}
if m, err = DecodeRGBA(data); err != nil {
return
}
return
}
|
[
"func",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"m",
"image",
".",
"Image",
",",
"err",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"m",
",",
"err",
"=",
"DecodeRGBA",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Decode reads a WEBP image from r and returns it as an image.Image.
|
[
"Decode",
"reads",
"a",
"WEBP",
"image",
"from",
"r",
"and",
"returns",
"it",
"as",
"an",
"image",
".",
"Image",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/reader.go#L87-L96
|
15,185 |
chai2010/webp
|
writer.go
|
Encode
|
func Encode(w io.Writer, m image.Image, opt *Options) (err error) {
return encode(w, m, opt)
}
|
go
|
func Encode(w io.Writer, m image.Image, opt *Options) (err error) {
return encode(w, m, opt)
}
|
[
"func",
"Encode",
"(",
"w",
"io",
".",
"Writer",
",",
"m",
"image",
".",
"Image",
",",
"opt",
"*",
"Options",
")",
"(",
"err",
"error",
")",
"{",
"return",
"encode",
"(",
"w",
",",
"m",
",",
"opt",
")",
"\n",
"}"
] |
// Encode writes the image m to w in WEBP format.
|
[
"Encode",
"writes",
"the",
"image",
"m",
"to",
"w",
"in",
"WEBP",
"format",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/writer.go#L41-L43
|
15,186 |
chai2010/webp
|
webp.go
|
DecodeGrayToSize
|
func DecodeGrayToSize(data []byte, width, height int) (m *image.Gray, err error) {
pix, err := webpDecodeGrayToSize(data, width, height)
if err != nil {
return
}
m = &image.Gray{
Pix: pix,
Stride: width,
Rect: image.Rect(0, 0, width, height),
}
return
}
|
go
|
func DecodeGrayToSize(data []byte, width, height int) (m *image.Gray, err error) {
pix, err := webpDecodeGrayToSize(data, width, height)
if err != nil {
return
}
m = &image.Gray{
Pix: pix,
Stride: width,
Rect: image.Rect(0, 0, width, height),
}
return
}
|
[
"func",
"DecodeGrayToSize",
"(",
"data",
"[",
"]",
"byte",
",",
"width",
",",
"height",
"int",
")",
"(",
"m",
"*",
"image",
".",
"Gray",
",",
"err",
"error",
")",
"{",
"pix",
",",
"err",
":=",
"webpDecodeGrayToSize",
"(",
"data",
",",
"width",
",",
"height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"m",
"=",
"&",
"image",
".",
"Gray",
"{",
"Pix",
":",
"pix",
",",
"Stride",
":",
"width",
",",
"Rect",
":",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
",",
"}",
"\n",
"return",
"\n",
"}"
] |
// DecodeGrayToSize decodes a Gray image scaled to the given dimensions. For
// large images, the DecodeXXXToSize methods are significantly faster and
// require less memory compared to decoding a full-size image and then resizing it.
|
[
"DecodeGrayToSize",
"decodes",
"a",
"Gray",
"image",
"scaled",
"to",
"the",
"given",
"dimensions",
".",
"For",
"large",
"images",
"the",
"DecodeXXXToSize",
"methods",
"are",
"significantly",
"faster",
"and",
"require",
"less",
"memory",
"compared",
"to",
"decoding",
"a",
"full",
"-",
"size",
"image",
"and",
"then",
"resizing",
"it",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/webp.go#L62-L73
|
15,187 |
chai2010/webp
|
webp.go
|
DecodeRGBToSize
|
func DecodeRGBToSize(data []byte, width, height int) (m *RGBImage, err error) {
pix, err := webpDecodeRGBToSize(data, width, height)
if err != nil {
return
}
m = &RGBImage{
XPix: pix,
XStride: 3 * width,
XRect: image.Rect(0, 0, width, height),
}
return
}
|
go
|
func DecodeRGBToSize(data []byte, width, height int) (m *RGBImage, err error) {
pix, err := webpDecodeRGBToSize(data, width, height)
if err != nil {
return
}
m = &RGBImage{
XPix: pix,
XStride: 3 * width,
XRect: image.Rect(0, 0, width, height),
}
return
}
|
[
"func",
"DecodeRGBToSize",
"(",
"data",
"[",
"]",
"byte",
",",
"width",
",",
"height",
"int",
")",
"(",
"m",
"*",
"RGBImage",
",",
"err",
"error",
")",
"{",
"pix",
",",
"err",
":=",
"webpDecodeRGBToSize",
"(",
"data",
",",
"width",
",",
"height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"m",
"=",
"&",
"RGBImage",
"{",
"XPix",
":",
"pix",
",",
"XStride",
":",
"3",
"*",
"width",
",",
"XRect",
":",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
",",
"}",
"\n",
"return",
"\n",
"}"
] |
// DecodeRGBToSize decodes an RGB image scaled to the given dimensions.
|
[
"DecodeRGBToSize",
"decodes",
"an",
"RGB",
"image",
"scaled",
"to",
"the",
"given",
"dimensions",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/webp.go#L76-L87
|
15,188 |
chai2010/webp
|
webp.go
|
DecodeRGBAToSize
|
func DecodeRGBAToSize(data []byte, width, height int) (m *image.RGBA, err error) {
pix, err := webpDecodeRGBAToSize(data, width, height)
if err != nil {
return
}
m = &image.RGBA{
Pix: pix,
Stride: 4 * width,
Rect: image.Rect(0, 0, width, height),
}
return
}
|
go
|
func DecodeRGBAToSize(data []byte, width, height int) (m *image.RGBA, err error) {
pix, err := webpDecodeRGBAToSize(data, width, height)
if err != nil {
return
}
m = &image.RGBA{
Pix: pix,
Stride: 4 * width,
Rect: image.Rect(0, 0, width, height),
}
return
}
|
[
"func",
"DecodeRGBAToSize",
"(",
"data",
"[",
"]",
"byte",
",",
"width",
",",
"height",
"int",
")",
"(",
"m",
"*",
"image",
".",
"RGBA",
",",
"err",
"error",
")",
"{",
"pix",
",",
"err",
":=",
"webpDecodeRGBAToSize",
"(",
"data",
",",
"width",
",",
"height",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"m",
"=",
"&",
"image",
".",
"RGBA",
"{",
"Pix",
":",
"pix",
",",
"Stride",
":",
"4",
"*",
"width",
",",
"Rect",
":",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
",",
"}",
"\n",
"return",
"\n",
"}"
] |
// DecodeRGBAToSize decodes a Gray image scaled to the given dimensions.
|
[
"DecodeRGBAToSize",
"decodes",
"a",
"Gray",
"image",
"scaled",
"to",
"the",
"given",
"dimensions",
"."
] |
19c584e49a98c31e2138c82fd0108435cd80d182
|
https://github.com/chai2010/webp/blob/19c584e49a98c31e2138c82fd0108435cd80d182/webp.go#L90-L101
|
15,189 |
franela/goblin
|
assertions.go
|
Equal
|
func (a *Assertion) Equal(dst interface{}) {
if !objectsAreEqual(a.src, dst) {
a.fail(fmt.Sprintf("%#v %s %#v", a.src, "does not equal", dst))
}
}
|
go
|
func (a *Assertion) Equal(dst interface{}) {
if !objectsAreEqual(a.src, dst) {
a.fail(fmt.Sprintf("%#v %s %#v", a.src, "does not equal", dst))
}
}
|
[
"func",
"(",
"a",
"*",
"Assertion",
")",
"Equal",
"(",
"dst",
"interface",
"{",
"}",
")",
"{",
"if",
"!",
"objectsAreEqual",
"(",
"a",
".",
"src",
",",
"dst",
")",
"{",
"a",
".",
"fail",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
".",
"src",
",",
"\"",
"\"",
",",
"dst",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Equal takes a destination object and asserts that a source object and
// destination object are equal to one another. It will fail the assertion and
// print a corresponding message if the objects are not equivalent.
|
[
"Equal",
"takes",
"a",
"destination",
"object",
"and",
"asserts",
"that",
"a",
"source",
"object",
"and",
"destination",
"object",
"are",
"equal",
"to",
"one",
"another",
".",
"It",
"will",
"fail",
"the",
"assertion",
"and",
"print",
"a",
"corresponding",
"message",
"if",
"the",
"objects",
"are",
"not",
"equivalent",
"."
] |
ead4ad1d27278780bab074b8dee47fba0e67afda
|
https://github.com/franela/goblin/blob/ead4ad1d27278780bab074b8dee47fba0e67afda/assertions.go#L46-L50
|
15,190 |
franela/goblin
|
assertions.go
|
IsTrue
|
func (a *Assertion) IsTrue(messages ...string) {
if !objectsAreEqual(a.src, true) {
message := fmt.Sprintf("%v %s%s", a.src, "expected false to be truthy", formatMessages(messages...))
a.fail(message)
}
}
|
go
|
func (a *Assertion) IsTrue(messages ...string) {
if !objectsAreEqual(a.src, true) {
message := fmt.Sprintf("%v %s%s", a.src, "expected false to be truthy", formatMessages(messages...))
a.fail(message)
}
}
|
[
"func",
"(",
"a",
"*",
"Assertion",
")",
"IsTrue",
"(",
"messages",
"...",
"string",
")",
"{",
"if",
"!",
"objectsAreEqual",
"(",
"a",
".",
"src",
",",
"true",
")",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
".",
"src",
",",
"\"",
"\"",
",",
"formatMessages",
"(",
"messages",
"...",
")",
")",
"\n",
"a",
".",
"fail",
"(",
"message",
")",
"\n",
"}",
"\n",
"}"
] |
// IsTrue asserts that a source is equal to true. Optional messages can be
// provided for inclusion in the displayed message if the assertion fails. It
// will fail the assertion if the source does not resolve to true.
|
[
"IsTrue",
"asserts",
"that",
"a",
"source",
"is",
"equal",
"to",
"true",
".",
"Optional",
"messages",
"can",
"be",
"provided",
"for",
"inclusion",
"in",
"the",
"displayed",
"message",
"if",
"the",
"assertion",
"fails",
".",
"It",
"will",
"fail",
"the",
"assertion",
"if",
"the",
"source",
"does",
"not",
"resolve",
"to",
"true",
"."
] |
ead4ad1d27278780bab074b8dee47fba0e67afda
|
https://github.com/franela/goblin/blob/ead4ad1d27278780bab074b8dee47fba0e67afda/assertions.go#L55-L60
|
15,191 |
franela/goblin
|
assertions.go
|
IsFalse
|
func (a *Assertion) IsFalse(messages ...string) {
if !objectsAreEqual(a.src, false) {
message := fmt.Sprintf("%v %s%s", a.src, "expected true to be falsey", formatMessages(messages...))
a.fail(message)
}
}
|
go
|
func (a *Assertion) IsFalse(messages ...string) {
if !objectsAreEqual(a.src, false) {
message := fmt.Sprintf("%v %s%s", a.src, "expected true to be falsey", formatMessages(messages...))
a.fail(message)
}
}
|
[
"func",
"(",
"a",
"*",
"Assertion",
")",
"IsFalse",
"(",
"messages",
"...",
"string",
")",
"{",
"if",
"!",
"objectsAreEqual",
"(",
"a",
".",
"src",
",",
"false",
")",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
".",
"src",
",",
"\"",
"\"",
",",
"formatMessages",
"(",
"messages",
"...",
")",
")",
"\n",
"a",
".",
"fail",
"(",
"message",
")",
"\n",
"}",
"\n",
"}"
] |
// IsFalse asserts that a source is equal to false. Optional messages can be
// provided for inclusion in the displayed message if the assertion fails. It
// will fail the assertion if the source does not resolve to false.
|
[
"IsFalse",
"asserts",
"that",
"a",
"source",
"is",
"equal",
"to",
"false",
".",
"Optional",
"messages",
"can",
"be",
"provided",
"for",
"inclusion",
"in",
"the",
"displayed",
"message",
"if",
"the",
"assertion",
"fails",
".",
"It",
"will",
"fail",
"the",
"assertion",
"if",
"the",
"source",
"does",
"not",
"resolve",
"to",
"false",
"."
] |
ead4ad1d27278780bab074b8dee47fba0e67afda
|
https://github.com/franela/goblin/blob/ead4ad1d27278780bab074b8dee47fba0e67afda/assertions.go#L65-L70
|
15,192 |
koding/websocketproxy
|
websocketproxy.go
|
NewProxy
|
func NewProxy(target *url.URL) *WebsocketProxy {
backend := func(r *http.Request) *url.URL {
// Shallow copy
u := *target
u.Fragment = r.URL.Fragment
u.Path = r.URL.Path
u.RawQuery = r.URL.RawQuery
return &u
}
return &WebsocketProxy{Backend: backend}
}
|
go
|
func NewProxy(target *url.URL) *WebsocketProxy {
backend := func(r *http.Request) *url.URL {
// Shallow copy
u := *target
u.Fragment = r.URL.Fragment
u.Path = r.URL.Path
u.RawQuery = r.URL.RawQuery
return &u
}
return &WebsocketProxy{Backend: backend}
}
|
[
"func",
"NewProxy",
"(",
"target",
"*",
"url",
".",
"URL",
")",
"*",
"WebsocketProxy",
"{",
"backend",
":=",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"url",
".",
"URL",
"{",
"// Shallow copy",
"u",
":=",
"*",
"target",
"\n",
"u",
".",
"Fragment",
"=",
"r",
".",
"URL",
".",
"Fragment",
"\n",
"u",
".",
"Path",
"=",
"r",
".",
"URL",
".",
"Path",
"\n",
"u",
".",
"RawQuery",
"=",
"r",
".",
"URL",
".",
"RawQuery",
"\n",
"return",
"&",
"u",
"\n",
"}",
"\n",
"return",
"&",
"WebsocketProxy",
"{",
"Backend",
":",
"backend",
"}",
"\n",
"}"
] |
// NewProxy returns a new Websocket reverse proxy that rewrites the
// URL's to the scheme, host and base path provider in target.
|
[
"NewProxy",
"returns",
"a",
"new",
"Websocket",
"reverse",
"proxy",
"that",
"rewrites",
"the",
"URL",
"s",
"to",
"the",
"scheme",
"host",
"and",
"base",
"path",
"provider",
"in",
"target",
"."
] |
7ed82d81a28c9ba1ed6fd1157ce714760f214c98
|
https://github.com/koding/websocketproxy/blob/7ed82d81a28c9ba1ed6fd1157ce714760f214c98/websocketproxy.go#L56-L66
|
15,193 |
antchfx/xmlquery
|
node.go
|
OutputXML
|
func (n *Node) OutputXML(self bool) string {
var buf bytes.Buffer
if self {
outputXML(&buf, n)
} else {
for n := n.FirstChild; n != nil; n = n.NextSibling {
outputXML(&buf, n)
}
}
return buf.String()
}
|
go
|
func (n *Node) OutputXML(self bool) string {
var buf bytes.Buffer
if self {
outputXML(&buf, n)
} else {
for n := n.FirstChild; n != nil; n = n.NextSibling {
outputXML(&buf, n)
}
}
return buf.String()
}
|
[
"func",
"(",
"n",
"*",
"Node",
")",
"OutputXML",
"(",
"self",
"bool",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"self",
"{",
"outputXML",
"(",
"&",
"buf",
",",
"n",
")",
"\n",
"}",
"else",
"{",
"for",
"n",
":=",
"n",
".",
"FirstChild",
";",
"n",
"!=",
"nil",
";",
"n",
"=",
"n",
".",
"NextSibling",
"{",
"outputXML",
"(",
"&",
"buf",
",",
"n",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// OutputXML returns the text that including tags name.
|
[
"OutputXML",
"returns",
"the",
"text",
"that",
"including",
"tags",
"name",
"."
] |
e401210509ad0f0492855c2066285c790860bd38
|
https://github.com/antchfx/xmlquery/blob/e401210509ad0f0492855c2066285c790860bd38/node.go#L116-L127
|
15,194 |
antchfx/xmlquery
|
node.go
|
LoadURL
|
func LoadURL(url string) (*Node, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return parse(resp.Body)
}
|
go
|
func LoadURL(url string) (*Node, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return parse(resp.Body)
}
|
[
"func",
"LoadURL",
"(",
"url",
"string",
")",
"(",
"*",
"Node",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"return",
"parse",
"(",
"resp",
".",
"Body",
")",
"\n",
"}"
] |
// LoadURL loads the XML document from the specified URL.
|
[
"LoadURL",
"loads",
"the",
"XML",
"document",
"from",
"the",
"specified",
"URL",
"."
] |
e401210509ad0f0492855c2066285c790860bd38
|
https://github.com/antchfx/xmlquery/blob/e401210509ad0f0492855c2066285c790860bd38/node.go#L171-L178
|
15,195 |
antchfx/xmlquery
|
query.go
|
CreateXPathNavigator
|
func CreateXPathNavigator(top *Node) *NodeNavigator {
return &NodeNavigator{curr: top, root: top, attr: -1}
}
|
go
|
func CreateXPathNavigator(top *Node) *NodeNavigator {
return &NodeNavigator{curr: top, root: top, attr: -1}
}
|
[
"func",
"CreateXPathNavigator",
"(",
"top",
"*",
"Node",
")",
"*",
"NodeNavigator",
"{",
"return",
"&",
"NodeNavigator",
"{",
"curr",
":",
"top",
",",
"root",
":",
"top",
",",
"attr",
":",
"-",
"1",
"}",
"\n",
"}"
] |
// CreateXPathNavigator creates a new xpath.NodeNavigator for the specified html.Node.
|
[
"CreateXPathNavigator",
"creates",
"a",
"new",
"xpath",
".",
"NodeNavigator",
"for",
"the",
"specified",
"html",
".",
"Node",
"."
] |
e401210509ad0f0492855c2066285c790860bd38
|
https://github.com/antchfx/xmlquery/blob/e401210509ad0f0492855c2066285c790860bd38/query.go#L48-L50
|
15,196 |
antchfx/xmlquery
|
query.go
|
Find
|
func Find(top *Node, expr string) []*Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elems []*Node
for t.MoveNext() {
elems = append(elems, getCurrentNode(t))
}
return elems
}
|
go
|
func Find(top *Node, expr string) []*Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elems []*Node
for t.MoveNext() {
elems = append(elems, getCurrentNode(t))
}
return elems
}
|
[
"func",
"Find",
"(",
"top",
"*",
"Node",
",",
"expr",
"string",
")",
"[",
"]",
"*",
"Node",
"{",
"exp",
",",
"err",
":=",
"xpath",
".",
"Compile",
"(",
"expr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"t",
":=",
"exp",
".",
"Select",
"(",
"CreateXPathNavigator",
"(",
"top",
")",
")",
"\n",
"var",
"elems",
"[",
"]",
"*",
"Node",
"\n",
"for",
"t",
".",
"MoveNext",
"(",
")",
"{",
"elems",
"=",
"append",
"(",
"elems",
",",
"getCurrentNode",
"(",
"t",
")",
")",
"\n",
"}",
"\n",
"return",
"elems",
"\n",
"}"
] |
// Find searches the Node that matches by the specified XPath expr.
|
[
"Find",
"searches",
"the",
"Node",
"that",
"matches",
"by",
"the",
"specified",
"XPath",
"expr",
"."
] |
e401210509ad0f0492855c2066285c790860bd38
|
https://github.com/antchfx/xmlquery/blob/e401210509ad0f0492855c2066285c790860bd38/query.go#L70-L81
|
15,197 |
antchfx/xmlquery
|
query.go
|
FindOne
|
func FindOne(top *Node, expr string) *Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elem *Node
if t.MoveNext() {
elem = getCurrentNode(t)
}
return elem
}
|
go
|
func FindOne(top *Node, expr string) *Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elem *Node
if t.MoveNext() {
elem = getCurrentNode(t)
}
return elem
}
|
[
"func",
"FindOne",
"(",
"top",
"*",
"Node",
",",
"expr",
"string",
")",
"*",
"Node",
"{",
"exp",
",",
"err",
":=",
"xpath",
".",
"Compile",
"(",
"expr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"t",
":=",
"exp",
".",
"Select",
"(",
"CreateXPathNavigator",
"(",
"top",
")",
")",
"\n",
"var",
"elem",
"*",
"Node",
"\n",
"if",
"t",
".",
"MoveNext",
"(",
")",
"{",
"elem",
"=",
"getCurrentNode",
"(",
"t",
")",
"\n",
"}",
"\n",
"return",
"elem",
"\n",
"}"
] |
// FindOne searches the Node that matches by the specified XPath expr,
// and returns first element of matched.
|
[
"FindOne",
"searches",
"the",
"Node",
"that",
"matches",
"by",
"the",
"specified",
"XPath",
"expr",
"and",
"returns",
"first",
"element",
"of",
"matched",
"."
] |
e401210509ad0f0492855c2066285c790860bd38
|
https://github.com/antchfx/xmlquery/blob/e401210509ad0f0492855c2066285c790860bd38/query.go#L85-L96
|
15,198 |
zsais/go-gin-prometheus
|
middleware.go
|
NewPrometheus
|
func NewPrometheus(subsystem string, customMetricsList ...[]*Metric) *Prometheus {
var metricsList []*Metric
if len(customMetricsList) > 1 {
panic("Too many args. NewPrometheus( string, <optional []*Metric> ).")
} else if len(customMetricsList) == 1 {
metricsList = customMetricsList[0]
}
for _, metric := range standardMetrics {
metricsList = append(metricsList, metric)
}
p := &Prometheus{
MetricsList: metricsList,
MetricsPath: defaultMetricPath,
ReqCntURLLabelMappingFn: func(c *gin.Context) string {
return c.Request.URL.String() // i.e. by default do nothing, i.e. return URL as is
},
}
p.registerMetrics(subsystem)
return p
}
|
go
|
func NewPrometheus(subsystem string, customMetricsList ...[]*Metric) *Prometheus {
var metricsList []*Metric
if len(customMetricsList) > 1 {
panic("Too many args. NewPrometheus( string, <optional []*Metric> ).")
} else if len(customMetricsList) == 1 {
metricsList = customMetricsList[0]
}
for _, metric := range standardMetrics {
metricsList = append(metricsList, metric)
}
p := &Prometheus{
MetricsList: metricsList,
MetricsPath: defaultMetricPath,
ReqCntURLLabelMappingFn: func(c *gin.Context) string {
return c.Request.URL.String() // i.e. by default do nothing, i.e. return URL as is
},
}
p.registerMetrics(subsystem)
return p
}
|
[
"func",
"NewPrometheus",
"(",
"subsystem",
"string",
",",
"customMetricsList",
"...",
"[",
"]",
"*",
"Metric",
")",
"*",
"Prometheus",
"{",
"var",
"metricsList",
"[",
"]",
"*",
"Metric",
"\n\n",
"if",
"len",
"(",
"customMetricsList",
")",
">",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"customMetricsList",
")",
"==",
"1",
"{",
"metricsList",
"=",
"customMetricsList",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"metric",
":=",
"range",
"standardMetrics",
"{",
"metricsList",
"=",
"append",
"(",
"metricsList",
",",
"metric",
")",
"\n",
"}",
"\n\n",
"p",
":=",
"&",
"Prometheus",
"{",
"MetricsList",
":",
"metricsList",
",",
"MetricsPath",
":",
"defaultMetricPath",
",",
"ReqCntURLLabelMappingFn",
":",
"func",
"(",
"c",
"*",
"gin",
".",
"Context",
")",
"string",
"{",
"return",
"c",
".",
"Request",
".",
"URL",
".",
"String",
"(",
")",
"// i.e. by default do nothing, i.e. return URL as is",
"\n",
"}",
",",
"}",
"\n\n",
"p",
".",
"registerMetrics",
"(",
"subsystem",
")",
"\n\n",
"return",
"p",
"\n",
"}"
] |
// NewPrometheus generates a new set of metrics with a certain subsystem name
|
[
"NewPrometheus",
"generates",
"a",
"new",
"set",
"of",
"metrics",
"with",
"a",
"certain",
"subsystem",
"name"
] |
58963fb32f547bd98cc0150a6bcbdf181a430967
|
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L122-L147
|
15,199 |
zsais/go-gin-prometheus
|
middleware.go
|
SetPushGateway
|
func (p *Prometheus) SetPushGateway(pushGatewayURL, metricsURL string, pushIntervalSeconds time.Duration) {
p.Ppg.PushGatewayURL = pushGatewayURL
p.Ppg.MetricsURL = metricsURL
p.Ppg.PushIntervalSeconds = pushIntervalSeconds
p.startPushTicker()
}
|
go
|
func (p *Prometheus) SetPushGateway(pushGatewayURL, metricsURL string, pushIntervalSeconds time.Duration) {
p.Ppg.PushGatewayURL = pushGatewayURL
p.Ppg.MetricsURL = metricsURL
p.Ppg.PushIntervalSeconds = pushIntervalSeconds
p.startPushTicker()
}
|
[
"func",
"(",
"p",
"*",
"Prometheus",
")",
"SetPushGateway",
"(",
"pushGatewayURL",
",",
"metricsURL",
"string",
",",
"pushIntervalSeconds",
"time",
".",
"Duration",
")",
"{",
"p",
".",
"Ppg",
".",
"PushGatewayURL",
"=",
"pushGatewayURL",
"\n",
"p",
".",
"Ppg",
".",
"MetricsURL",
"=",
"metricsURL",
"\n",
"p",
".",
"Ppg",
".",
"PushIntervalSeconds",
"=",
"pushIntervalSeconds",
"\n",
"p",
".",
"startPushTicker",
"(",
")",
"\n",
"}"
] |
// SetPushGateway sends metrics to a remote pushgateway exposed on pushGatewayURL
// every pushIntervalSeconds. Metrics are fetched from metricsURL
|
[
"SetPushGateway",
"sends",
"metrics",
"to",
"a",
"remote",
"pushgateway",
"exposed",
"on",
"pushGatewayURL",
"every",
"pushIntervalSeconds",
".",
"Metrics",
"are",
"fetched",
"from",
"metricsURL"
] |
58963fb32f547bd98cc0150a6bcbdf181a430967
|
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L151-L156
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.