_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q15100
GetClipboard
train
func (e *Editor) GetClipboard() string { s, _ := e.clipboard.Get() return s }
go
{ "resource": "" }
q15101
SetClipboard
train
func (e *Editor) SetClipboard(s string) { e.clipboard.Set(s, false) }
go
{ "resource": "" }
q15102
UseMiddleware
train
func (api *API) UseMiddleware(middleware ...HandlerFunc) { api.middlewares = append(api.middlewares, middleware...) }
go
{ "resource": "" }
q15103
NewAPIVersion
train
func (api *API) NewAPIVersion(prefix string) *API { return newAPI(prefix, api.info.resolver, api.router) }
go
{ "resource": "" }
q15104
NewAPIWithResolver
train
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
{ "resource": "" }
q15105
NewAPI
train
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
{ "resource": "" }
q15106
newAPI
train
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
{ "resource": "" }
q15107
middlewareChain
train
func (api *API) middlewareChain(c APIContexter, w http.ResponseWriter, r *http.Request) { for _, middleware := range api.middlewares { middleware(c, w, r) } }
go
{ "resource": "" }
q15108
handleLinked
train
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
{ "resource": "" }
q15109
Links
train
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
{ "resource": "" }
q15110
Insert
train
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
{ "resource": "" }
q15111
GetBaseURL
train
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
{ "resource": "" }
q15112
FindAll
train
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
{ "resource": "" }
q15113
PaginatedFindAll
train
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
{ "resource": "" }
q15114
FindOne
train
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
{ "resource": "" }
q15115
Create
train
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
{ "resource": "" }
q15116
Delete
train
func (s UserResource) Delete(id string, r api2go.Request) (api2go.Responder, error) { err := s.UserStorage.Delete(id) return &Response{Code: http.StatusNoContent}, err }
go
{ "resource": "" }
q15117
Update
train
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
{ "resource": "" }
q15118
GetReferencedIDs
train
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
{ "resource": "" }
q15119
GetReferencedStructs
train
func (u User) GetReferencedStructs() []jsonapi.MarshalIdentifier { result := []jsonapi.MarshalIdentifier{} for key := range u.Chocolates { result = append(result, u.Chocolates[key]) } return result }
go
{ "resource": "" }
q15120
SetToManyReferenceIDs
train
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
{ "resource": "" }
q15121
AddToManyIDs
train
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
{ "resource": "" }
q15122
DeleteToManyIDs
train
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
{ "resource": "" }
q15123
Handle
train
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
{ "resource": "" }
q15124
GetRouteParameter
train
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
{ "resource": "" }
q15125
Set
train
func (c *APIContext) Set(key string, value interface{}) { if c.keys == nil { c.keys = make(map[string]interface{}) } c.keys[key] = value }
go
{ "resource": "" }
q15126
Get
train
func (c *APIContext) Get(key string) (value interface{}, exists bool) { if c.keys != nil { value, exists = c.keys[key] } return }
go
{ "resource": "" }
q15127
ContextQueryParams
train
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
{ "resource": "" }
q15128
Create
train
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
{ "resource": "" }
q15129
Update
train
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
{ "resource": "" }
q15130
Unmarshal
train
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
{ "resource": "" }
q15131
setRelationshipIDs
train
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
{ "resource": "" }
q15132
GetAll
train
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
{ "resource": "" }
q15133
GetOne
train
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
{ "resource": "" }
q15134
Insert
train
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
{ "resource": "" }
q15135
Update
train
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
{ "resource": "" }
q15136
UnmarshalJSON
train
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
{ "resource": "" }
q15137
MarshalJSON
train
func (c *DataContainer) MarshalJSON() ([]byte, error) { if c.DataArray != nil { return json.Marshal(c.DataArray) } return json.Marshal(c.DataObject) }
go
{ "resource": "" }
q15138
UnmarshalJSON
train
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
{ "resource": "" }
q15139
MarshalJSON
train
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
{ "resource": "" }
q15140
marshalHTTPError
train
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
{ "resource": "" }
q15141
Error
train
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
{ "resource": "" }
q15142
Jsonify
train
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
{ "resource": "" }
q15143
MarshalWithURLs
train
func MarshalWithURLs(data interface{}, information ServerInformation) ([]byte, error) { document, err := MarshalToStruct(data, information) if err != nil { return nil, err } return json.Marshal(document) }
go
{ "resource": "" }
q15144
Marshal
train
func Marshal(data interface{}) ([]byte, error) { document, err := MarshalToStruct(data, nil) if err != nil { return nil, err } return json.Marshal(document) }
go
{ "resource": "" }
q15145
FmtTimeMedium
train
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
{ "resource": "" }
q15146
FmtTimeFull
train
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
{ "resource": "" }
q15147
FmtTimeLong
train
func (tzm *tzm) FmtTimeLong(t time.Time) string { b := make([]byte, 0, 32) return string(b) }
go
{ "resource": "" }
q15148
FmtDateShort
train
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
{ "resource": "" }
q15149
String
train
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
{ "resource": "" }
q15150
F
train
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
{ "resource": "" }
q15151
T
train
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
{ "resource": "" }
q15152
pluralStringToInt
train
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
{ "resource": "" }
q15153
leaf0x80000004
train
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
{ "resource": "" }
q15154
ExtractOrgHeaders
train
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
{ "resource": "" }
q15155
OrgHeaders
train
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
{ "resource": "" }
q15156
NewParser
train
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
{ "resource": "" }
q15157
OrgCommon
train
func OrgCommon(input []byte) []byte { renderer := blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML, "", "") return OrgOptions(input, renderer) }
go
{ "resource": "" }
q15158
Org
train
func Org(input []byte, renderer blackfriday.Renderer) []byte { return OrgOptions(input, renderer) }
go
{ "resource": "" }
q15159
IsKeyword
train
func IsKeyword(data []byte) bool { return len(data) > 2 && charMatches(data[0], '#') && charMatches(data[1], '+') && !charMatches(data[2], ' ') }
go
{ "resource": "" }
q15160
generateVerbatim
train
func generateVerbatim(p *parser, out *bytes.Buffer, data []byte, offset int) int { return generator(p, out, data, offset, '=', false, p.r.CodeSpan) }
go
{ "resource": "" }
q15161
AddToEncoder
train
func (tc *customTypeConverter) AddToEncoder(e *Encoder) *Encoder { e.tc = tc return e }
go
{ "resource": "" }
q15162
Encode
train
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
{ "resource": "" }
q15163
Str2JSType
train
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
{ "resource": "" }
q15164
Convert
train
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
{ "resource": "" }
q15165
AddChild
train
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
{ "resource": "" }
q15166
GetChild
train
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
{ "resource": "" }
q15167
Decode
train
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
{ "resource": "" }
q15168
trimNonGraphic
train
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
{ "resource": "" }
q15169
Null
train
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
{ "resource": "" }
q15170
PackWithOrder
train
func PackWithOrder(w io.Writer, data interface{}, order binary.ByteOrder) error { return PackWithOptions(w, data, &Options{Order: order}) }
go
{ "resource": "" }
q15171
UnpackWithOrder
train
func UnpackWithOrder(r io.Reader, data interface{}, order binary.ByteOrder) error { return UnpackWithOptions(r, data, &Options{Order: order}) }
go
{ "resource": "" }
q15172
new
train
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
{ "resource": "" }
q15173
Clone
train
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
{ "resource": "" }
q15174
maybeToNormal
train
func (sk *Sketch) maybeToNormal() { if uint32(len(sk.tmpSet))*100 > sk.m { sk.mergeSparse() if uint32(sk.sparseList.Len()) > sk.m { sk.toNormal() } } }
go
{ "resource": "" }
q15175
Merge
train
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
{ "resource": "" }
q15176
toNormal
train
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
{ "resource": "" }
q15177
Insert
train
func (sk *Sketch) Insert(e []byte) bool { x := hash(e) return sk.InsertHash(x) }
go
{ "resource": "" }
q15178
InsertHash
train
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
{ "resource": "" }
q15179
Estimate
train
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
{ "resource": "" }
q15180
AsMemPImage
train
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
{ "resource": "" }
q15181
NewRGBImage
train
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
{ "resource": "" }
q15182
NewRGB48Image
train
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
{ "resource": "" }
q15183
DecodeConfig
train
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
{ "resource": "" }
q15184
Decode
train
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
{ "resource": "" }
q15185
Encode
train
func Encode(w io.Writer, m image.Image, opt *Options) (err error) { return encode(w, m, opt) }
go
{ "resource": "" }
q15186
DecodeGrayToSize
train
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
{ "resource": "" }
q15187
DecodeRGBToSize
train
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
{ "resource": "" }
q15188
DecodeRGBAToSize
train
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
{ "resource": "" }
q15189
Equal
train
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
{ "resource": "" }
q15190
IsTrue
train
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
{ "resource": "" }
q15191
IsFalse
train
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
{ "resource": "" }
q15192
NewProxy
train
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
{ "resource": "" }
q15193
OutputXML
train
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
{ "resource": "" }
q15194
LoadURL
train
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
{ "resource": "" }
q15195
CreateXPathNavigator
train
func CreateXPathNavigator(top *Node) *NodeNavigator { return &NodeNavigator{curr: top, root: top, attr: -1} }
go
{ "resource": "" }
q15196
Find
train
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
{ "resource": "" }
q15197
FindOne
train
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
{ "resource": "" }
q15198
NewPrometheus
train
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
{ "resource": "" }
q15199
SetPushGateway
train
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
{ "resource": "" }