_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L164-L176
func (api *TelegramBotAPI) NewOutgoingVoiceResend(recipient Recipient, fileID string) *OutgoingVoice { return &OutgoingVoice{ outgoingMessageBase: outgoingMessageBase{ outgoingBase: outgoingBase{ api: api, Recipient: recipient, }, }, outgoingFileBase: outgoingFileBase{ fileID: fileID, }, } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L219-L223
func (eC2Manager *EC2Manager) TerminateInstance(region, instanceId string) error { cd := tcclient.Client(*eC2Manager) _, _, err := (&cd).APICall(nil, "DELETE", "/region/"+url.QueryEscape(region)+"/instance/"+url.QueryEscape(instanceId), nil, nil) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L735-L739
func (v *EventNetworkStateUpdated) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache8(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L2287-L2291
func (v EventConsoleProfileStarted) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler22(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-encode.go#L443-L457
func isEmpty(rv reflect.Value, zrv reflect.Value) bool { if !rv.IsValid() { return true } if reflect.DeepEqual(rv.Interface(), zrv.Interface()) { return true } switch rv.Kind() { case reflect.Slice, reflect.Array, reflect.String: if rv.Len() == 0 { return true } } return false }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L245-L250
func NewThrottle(max int) *Throttle { return &Throttle{ ch: make(chan struct{}, max), errCh: make(chan error, max), } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/tcqueue.go#L769-L780
func (queue *Queue) ListArtifacts(taskId, runId, continuationToken, limit string) (*ListArtifactsResponse, error) { v := url.Values{} if continuationToken != "" { v.Add("continuationToken", continuationToken) } if limit != "" { v.Add("limit", limit) } cd := tcclient.Client(*queue) responseObject, _, err := (&cd).APICall(nil, "GET", "/task/"+url.QueryEscape(taskId)+"/runs/"+url.QueryEscape(runId)+"/artifacts", new(ListArtifactsResponse), v) return responseObject.(*ListArtifactsResponse), err }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L320-L323
func (gc *GraphicContext) SetLineJoin(Join draw2d.LineJoin) { gc.StackGraphicContext.SetLineJoin(Join) gc.pdf.SetLineJoinStyle(joins[Join]) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L62-L75
func socketUnixRemoveStale(path string) error { // If there's no socket file at all, there's nothing to do. if !shared.PathExists(path) { return nil } logger.Debugf("Detected stale unix socket, deleting") err := os.Remove(path) if err != nil { return fmt.Errorf("could not delete stale local socket: %v", err) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L408-L414
func TxCommit(tx *sql.Tx) error { err := tx.Commit() if err == nil || err == sql.ErrTxDone { // Ignore duplicate commits/rollbacks return nil } return err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L694-L698
func (c *Cluster) ImageAliasUpdate(id int, imageID int, desc string) error { stmt := `UPDATE images_aliases SET image_id=?, description=? WHERE id=?` err := exec(c.db, stmt, imageID, desc, id) return err }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/value.go#L74-L94
func (lf *logFile) openReadOnly() error { var err error lf.fd, err = os.OpenFile(lf.path, os.O_RDONLY, 0666) if err != nil { return errors.Wrapf(err, "Unable to open %q as RDONLY.", lf.path) } fi, err := lf.fd.Stat() if err != nil { return errors.Wrapf(err, "Unable to check stat for %q", lf.path) } y.AssertTrue(fi.Size() <= math.MaxUint32) lf.size = uint32(fi.Size()) if err = lf.mmap(fi.Size()); err != nil { _ = lf.fd.Close() return y.Wrapf(err, "Unable to map file") } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/types.go#L135-L137
func (t *VersionStatus) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/host.go#L317-L347
func (h *Host) CopyFileToGuest(src string, guest *Guest, dest string) error { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK csrc := C.CString(src) cdest := C.CString(dest) defer C.free(unsafe.Pointer(csrc)) defer C.free(unsafe.Pointer(cdest)) jobHandle = C.VixVM_CopyFileFromHostToGuest( guest.handle, // VM handle csrc, // src name cdest, // dest name C.int(0), // options C.VIX_INVALID_HANDLE, // propertyListHandle nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.vix_job_wait(jobHandle) if C.VIX_OK != err { return &Error{ Operation: "host.CopyFileToGuest", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/capabilities.go#L17-L23
func NewCapabilities(features ...string) Capabilities { c := Capabilities{} for _, feature := range features { c.With(feature) } return c }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L93-L102
func NewResource(name, rtype, state, owner string, t time.Time) Resource { return Resource{ Name: name, Type: rtype, State: state, Owner: owner, LastUpdate: t, UserData: &UserData{}, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L272-L288
func SetProjectQuota(path string, id uint32, bytes int64) error { // Get the backing device devPath, err := devForPath(path) if err != nil { return err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) if C.quota_set(cDevPath, C.uint32_t(id), C.int(bytes/1024)) != 0 { return fmt.Errorf("Failed to set project quota for id '%d' on '%s'", id, path) } return nil }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/types.go#L494-L497
func (this *LaunchInfo) MarshalJSON() ([]byte, error) { x := json.RawMessage(*this) return (&x).MarshalJSON() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1563-L1580
func NewChildCursor(tx *bolt.Tx, path string) *ChildCursor { path = clean(path) c := fs(tx).Cursor() dir := b(path) k, v := c.Seek(append(dir, nullByte[0])) if !bytes.Equal(dir, nullByte) { dir = append(dir, nullByte[0]) } if !bytes.HasPrefix(k, dir) { k, v = nil, nil } return &ChildCursor{ c: c, dir: dir, k: k, v: v, } }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L422-L448
func (c *Consumer) twLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Metadata.RefreshFrequency / 2) defer ticker.Stop() for { select { case <-ticker.C: topics, err := c.client.Topics() if err != nil { c.handleError(&Error{Ctx: "topics", error: err}) return } for _, topic := range topics { if !c.isKnownCoreTopic(topic) && !c.isKnownExtraTopic(topic) && c.isPotentialExtraTopic(topic) { return } } case <-stopped: return case <-c.dying: return } } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/grpcutil/stream.go#L131-L136
func WriteToStreamingBytesServer(reader io.Reader, streamingBytesServer StreamingBytesServer) error { buf := GetBuffer() defer PutBuffer(buf) _, err := io.CopyBuffer(NewStreamingBytesWriter(streamingBytesServer), ReaderWrapper{reader}, buf) return err }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L762-L764
func Infof(format string, val ...interface{}) error { return glg.out(INFO, format, val...) }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/security/nonce.go#L63-L67
func Getter(g NonceGetter) Option { return Option{func(o *options) { o.getter = g }} }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L77-L86
func (d *DefaultContext) Value(key interface{}) interface{} { if k, ok := key.(string); ok { d.moot.RLock() defer d.moot.RUnlock() if v, ok := d.data[k]; ok { return v } } return d.Context.Value(key) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/fetch_repo/module.go#L293-L307
func isSemverPrefix(v string) bool { dots := 0 for i := 0; i < len(v); i++ { switch v[i] { case '-', '+': return false case '.': dots++ if dots >= 2 { return false } } } return true }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L139-L175
func (s *Storage) Get(ctx context.Context, accessToken string) (*mnemosynerpc.Session, error) { span, ctx := opentracing.StartSpanFromContext(ctx, "postgres.storage.get") defer span.Finish() var entity sessionEntity start := time.Now() labels := prometheus.Labels{"query": "get"} err := s.db.QueryRowContext(ctx, s.queryGet, accessToken).Scan( &entity.RefreshToken, &entity.SubjectID, &entity.SubjectClient, &entity.Bag, &entity.ExpireAt, ) s.incQueries(labels, start) if err != nil { s.incError(labels) if err == sql.ErrNoRows { return nil, storage.ErrSessionNotFound } return nil, err } expireAt, err := ptypes.TimestampProto(entity.ExpireAt) if err != nil { return nil, err } return &mnemosynerpc.Session{ AccessToken: accessToken, RefreshToken: entity.RefreshToken, SubjectId: entity.SubjectID, SubjectClient: entity.SubjectClient, Bag: entity.Bag, ExpireAt: expireAt, }, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1011-L1015
func (v *StartParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler12(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1300-L1304
func (v Key) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L207-L227
func (ctx *Context) SetSession(key string, values map[string]string) error { sid := ctx.genSid(key) values["Sid"] = sid timestamp := strconv.FormatInt(time.Now().Unix(), 10) token := ctx.genSid(key + timestamp) values["Token"] = token store, err := provider.Set(sid, values) if err != nil { return err } cookie := httpCookie cookie.Value = sid ctx.Data["session"] = store respCookie := ctx.ResponseWriter.Header().Get("Set-Cookie") if strings.HasPrefix(respCookie, cookie.Name) { ctx.ResponseWriter.Header().Del("Set-Cookie") } http.SetCookie(ctx.ResponseWriter, &cookie) return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L72-L82
func (r *ProtocolLXD) GetContainer(name string) (*api.Container, string, error) { container := api.Container{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s", url.QueryEscape(name)), nil, "", &container) if err != nil { return nil, "", err } return &container, etag, nil }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/group.go#L43-L59
func (g *Group) Add(controllers ...*Controller) { for _, controller := range controllers { // prepare controller controller.prepare() // get name name := controller.Model.Meta().PluralName // check existence if g.controllers[name] != nil { panic(fmt.Sprintf(`fire: controller with name "%s" already exists`, name)) } // create entry in controller map g.controllers[name] = controller } }
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L278-L297
func (gi *GeoIP) GetNameV6(ip string) (name string, netmask int) { if gi.db == nil { return } gi.mu.Lock() defer gi.mu.Unlock() cip := C.CString(ip) defer C.free(unsafe.Pointer(cip)) cname := C.GeoIP_name_by_addr_v6(gi.db, cip) if cname != nil { name = C.GoString(cname) defer C.free(unsafe.Pointer(cname)) netmask = int(C.GeoIP_last_netmask(gi.db)) return } return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L443-L463
func (c APIClient) DeleteAll() error { if _, err := c.AuthAPIClient.Deactivate( c.Ctx(), &auth.DeactivateRequest{}, ); err != nil && !auth.IsErrNotActivated(err) { return grpcutil.ScrubGRPC(err) } if _, err := c.PpsAPIClient.DeleteAll( c.Ctx(), &types.Empty{}, ); err != nil { return grpcutil.ScrubGRPC(err) } if _, err := c.PfsAPIClient.DeleteAll( c.Ctx(), &types.Empty{}, ); err != nil { return grpcutil.ScrubGRPC(err) } return nil }
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/password_strength.go#L41-L59
func (p *PasswordStrengthRequirements) Validate(password string) (bool, string) { reqs := MakeRequirements(password) if p.MaximumTotalLength > 0 && reqs.MaximumTotalLength > p.MaximumTotalLength { return false, "password is too long" } if reqs.MinimumTotalLength < p.MinimumTotalLength { return false, "password is too short" } if reqs.Digits < p.Digits { return false, "password has too few digits" } if reqs.Punctuation < p.Punctuation { return false, "password has too few punctuation characters" } if reqs.Uppercase < p.Uppercase { return false, "password has too few uppercase characters" } return true, "" }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/app.go#L35-L74
func New(opts Options) *App { LoadPlugins() envy.Load() opts = optionsWithDefaults(opts) a := &App{ Options: opts, ErrorHandlers: ErrorHandlers{ 404: defaultErrorHandler, 500: defaultErrorHandler, }, router: mux.NewRouter(), moot: &sync.RWMutex{}, routes: RouteList{}, children: []*App{}, } dem := a.defaultErrorMiddleware a.Middleware = newMiddlewareStack(dem) notFoundHandler := func(errorf string, code int) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { c := a.newContext(RouteInfo{}, res, req) err := fmt.Errorf(errorf, req.Method, req.URL.Path) a.ErrorHandlers.Get(code)(code, err, c) } } a.router.NotFoundHandler = notFoundHandler("path not found: %s %s", 404) a.router.MethodNotAllowedHandler = notFoundHandler("method not found: %s %s", 405) if a.MethodOverride == nil { a.MethodOverride = MethodOverride } a.Use(a.PanicHandler) a.Use(RequestLogger) a.Use(sessionSaver) return a }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/pool.go#L328-L362
func poolConstraintSet(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { if !permission.Check(t, permission.PermPoolUpdateConstraintsSet) { return permission.ErrUnauthorized } var poolConstraint pool.PoolConstraint err = ParseInput(r, &poolConstraint) if err != nil { return err } if poolConstraint.PoolExpr == "" { return &terrors.HTTP{ Code: http.StatusBadRequest, Message: "You must provide a Pool Expression", } } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypePool, Value: poolConstraint.PoolExpr}, Kind: permission.PermPoolUpdateConstraintsSet, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermPoolReadEvents), }) if err != nil { return err } defer func() { evt.Done(err) }() append := false if appendStr := InputValue(r, "append"); appendStr != "" { append, _ = strconv.ParseBool(appendStr) } if append { return pool.AppendPoolConstraint(&poolConstraint) } return pool.SetPoolConstraint(&poolConstraint) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L69-L76
func (r *Account) Locator(api *API) *AccountLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.AccountLocator(l["href"]) } } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/mail/mail.go#L68-L70
func Send(c context.Context, msg *Message) error { return send(c, "Send", msg) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L510-L518
func resourceType(resName string) string { if resName == "ChildAccounts" { return "Account" } if _, ok := noMediaTypeResources[resName]; ok { return "map[string]interface{}" } return inflect.Singularize(resName) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/say_matcher.go#L38-L45
func Say(expected string, args ...interface{}) *sayMatcher { if len(args) > 0 { expected = fmt.Sprintf(expected, args...) } return &sayMatcher{ re: regexp.MustCompile(expected), } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L151-L194
func parseStruct(str *ast.StructType) ([]*Field, error) { fields := make([]*Field, 0) for _, f := range str.Fields.List { if len(f.Names) == 0 { // Check if this is a parent struct. ident, ok := f.Type.(*ast.Ident) if !ok { continue } typ, ok := ident.Obj.Decl.(*ast.TypeSpec) if !ok { continue } parentStr, ok := typ.Type.(*ast.StructType) if !ok { continue } parentFields, err := parseStruct(parentStr) if err != nil { return nil, errors.Wrapf(err, "Failed to parse parent struct") } fields = append(fields, parentFields...) continue } if len(f.Names) != 1 { return nil, fmt.Errorf("Expected a single field name, got %q", f.Names) } field, err := parseField(f) if err != nil { return nil, err } fields = append(fields, field) } return fields, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/template/chroot.go#L22-L24
func (l ChrootLoader) Abs(base string, name string) string { return filepath.Clean(fmt.Sprintf("%s/%s", l.Path, name)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/apparmor.go#L9-L16
func AppArmorProfile() string { contents, err := ioutil.ReadFile("/proc/self/attr/current") if err == nil { return strings.TrimSpace(string(contents)) } return "" }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L425-L427
func (p *SetShowPaintRectsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetShowPaintRects, p, nil) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_transport.go#L50-L60
func ParseReference(refString string) (types.ImageReference, error) { if !strings.HasPrefix(refString, "//") { return nil, errors.Errorf("docker: image reference %s does not start with //", refString) } ref, err := reference.ParseNormalizedNamed(strings.TrimPrefix(refString, "//")) if err != nil { return nil, err } ref = reference.TagNameOnly(ref) return NewReference(ref) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L281-L283
func (r *Datacenter) Locator(api *API) *DatacenterLocator { return api.DatacenterLocator(r.Href) }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L107-L117
func (op *outgoingBase) getBaseQueryString() querystring { toReturn := map[string]string{} if op.Recipient.isChannel() { //Channel toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChannelID) } else { toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChatID) } return querystring(toReturn) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L744-L757
func (n *netPipeline) Close() error { n.shutdownLock.Lock() defer n.shutdownLock.Unlock() if n.shutdown { return nil } // Release the connection n.conn.Release() n.shutdown = true close(n.shutdownCh) return nil }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/service/logger/logger.go#L209-L221
func (c Context) MarshalLogObject(enc zapcore.ObjectEncoder) error { if c.HTTPRequest != emptyHTTPRequest { enc.AddObject("httpRequest", c.HTTPRequest) } if c.User != "" { enc.AddString("user", c.User) } if c.reportLocation != emptyReportLocation { enc.AddObject("reportLocation", c.reportLocation) } return nil }
https://github.com/coreos/go-semver/blob/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver/semver.go#L147-L152
func (v Version) Compare(versionB Version) int { if cmp := recursiveCompare(v.Slice(), versionB.Slice()); cmp != 0 { return cmp } return preReleaseCompare(v, versionB) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/types.go#L118-L130
func (t *ScrollRectType) UnmarshalEasyJSON(in *jlexer.Lexer) { switch ScrollRectType(in.String()) { case ScrollRectTypeRepaintsOnScroll: *t = ScrollRectTypeRepaintsOnScroll case ScrollRectTypeTouchEventHandler: *t = ScrollRectTypeTouchEventHandler case ScrollRectTypeWheelEventHandler: *t = ScrollRectTypeWheelEventHandler default: in.AddError(errors.New("unknown ScrollRectType value")) } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L935-L949
func newImage(ctx context.Context, sys *types.SystemContext, s storageReference) (types.ImageCloser, error) { src, err := newImageSource(s) if err != nil { return nil, err } img, err := image.FromSource(ctx, sys, src) if err != nil { return nil, err } size, err := src.getSize() if err != nil { return nil, err } return &storageImageCloser{ImageCloser: img, size: size}, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1954-L1962
func (u OperationBody) MustSetOptionsOp() SetOptionsOp { val, ok := u.GetSetOptionsOp() if !ok { panic("arm SetOptionsOp is not set") } return val }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L355-L360
func (cdc *Codec) MustUnmarshalBinaryBare(bz []byte, ptr interface{}) { err := cdc.UnmarshalBinaryBare(bz, ptr) if err != nil { panic(err) } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcnotify/tcnotify.go#L96-L100
func (notify *Notify) Ping() error { cd := tcclient.Client(*notify) _, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil) return err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L152-L209
func Accept(state *state.State, gateway *Gateway, name, address string, schema, api int) ([]db.RaftNode, error) { // Check parameters if name == "" { return nil, fmt.Errorf("node name must not be empty") } if address == "" { return nil, fmt.Errorf("node address must not be empty") } // Insert the new node into the nodes table. err := state.Cluster.Transaction(func(tx *db.ClusterTx) error { // Check that the node can be accepted with these parameters. err := membershipCheckClusterStateForAccept(tx, name, address, schema, api) if err != nil { return err } // Add the new node id, err := tx.NodeAdd(name, address) if err != nil { return errors.Wrap(err, "failed to insert new node") } // Mark the node as pending, so it will be skipped when // performing heartbeats or sending cluster // notifications. err = tx.NodePending(id, true) if err != nil { return errors.Wrap(err, "failed to mark new node as pending") } return nil }) if err != nil { return nil, err } // Possibly insert the new node into the raft_nodes table (if we have // less than 3 database nodes). nodes, err := gateway.currentRaftNodes() if err != nil { return nil, errors.Wrap(err, "failed to get raft nodes from the log") } if len(nodes) < membershipMaxRaftNodes { err = state.Node.Transaction(func(tx *db.NodeTx) error { id, err := tx.RaftNodeAdd(address) if err != nil { return err } nodes = append(nodes, db.RaftNode{ID: id, Address: address}) return nil }) if err != nil { return nil, errors.Wrap(err, "failed to insert new node into raft_nodes") } } return nodes, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/fetcher.go#L50-L72
func (f *Fetcher) fetchRecentIssues(db *gorm.DB) error { glog.Infof("Fetching issues updated after %s", f.lastIssue) var issues []sql.Issue query := db. Where("issue_updated_at >= ?", f.lastIssue). Where("repository = ?", f.repository). Order("issue_updated_at"). Preload("Labels"). Find(&issues) if query.Error != nil { return query.Error } count := len(issues) for _, issue := range issues { f.IssuesChannel <- issue f.lastIssue = issue.IssueUpdatedAt } glog.Infof("Found and pushed %d updated/new issues", count) return nil }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/format.go#L41-L67
func fix(v interface{}) interface{} { if v == nil { return "<nil>" } switch reflect.TypeOf(v).Kind() { case reflect.Bool: case reflect.Int: case reflect.Int8: case reflect.Int16: case reflect.Int32: case reflect.Int64: case reflect.Uint: case reflect.Uint8: case reflect.Uint16: case reflect.Uint32: case reflect.Uint64: case reflect.Uintptr: case reflect.Float32: case reflect.Float64: return v case reflect.Ptr: // dereference and fix return fix(reflect.ValueOf(v).Elem()) } return fmt.Sprintf("%v", v) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L99-L112
func (p *Painter) SetColor(c color.Color) { r, g, b, a := c.RGBA() if a == 0 { p.cr = 0 p.cg = 0 p.cb = 0 p.ca = a } else { p.cr = uint8((r * M16 / a) >> 8) p.cg = uint8((g * M16 / a) >> 8) p.cb = uint8((b * M16 / a) >> 8) p.ca = a } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L1143-L1147
func (v *MakeSnapshotParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree11(&r, v) return r.Error() }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/taskqueue/taskqueue.go#L285-L304
func Add(c context.Context, task *Task, queueName string) (*Task, error) { req, err := newAddReq(c, task, queueName) if err != nil { return nil, err } res := &pb.TaskQueueAddResponse{} if err := internal.Call(c, "taskqueue", "Add", req, res); err != nil { apiErr, ok := err.(*internal.APIError) if ok && alreadyAddedErrors[pb.TaskQueueServiceError_ErrorCode(apiErr.Code)] { return nil, ErrTaskAlreadyAdded } return nil, err } resultTask := *task resultTask.Method = task.method() if task.Name == "" { resultTask.Name = string(res.ChosenTaskName) } return &resultTask, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5537-L5541
func (v *EventWebSocketFrameReceived) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork43(&r, v) return r.Error() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1153-L1161
func (app *App) setEnv(env bind.EnvVar) { if app.Env == nil { app.Env = make(map[string]bind.EnvVar) } app.Env[env.Name] = env if env.Public { app.Log(fmt.Sprintf("setting env %s with value %s", env.Name, env.Value), "tsuru", "api") } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/types/devices.go#L29-L77
func (list Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device, []string) { rmlist := map[string]Device{} addlist := map[string]Device{} updatelist := map[string]Device{} for key, d := range list { if !newlist.Contains(key, d) { rmlist[key] = d } } for key, d := range newlist { if !list.Contains(key, d) { addlist[key] = d } } updateDiff := []string{} for key, d := range addlist { srcOldDevice := rmlist[key] var oldDevice Device err := shared.DeepCopy(&srcOldDevice, &oldDevice) if err != nil { continue } srcNewDevice := newlist[key] var newDevice Device err = shared.DeepCopy(&srcNewDevice, &newDevice) if err != nil { continue } updateDiff = deviceEqualsDiffKeys(oldDevice, newDevice) for _, k := range []string{"limits.max", "limits.read", "limits.write", "limits.egress", "limits.ingress", "ipv4.address", "ipv6.address", "ipv4.routes", "ipv6.routes"} { delete(oldDevice, k) delete(newDevice, k) } if deviceEquals(oldDevice, newDevice) { delete(rmlist, key) delete(addlist, key) updatelist[key] = d } } return rmlist, addlist, updatelist, updateDiff }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/save.go#L38-L112
func valueToProto(defaultAppID, name string, v reflect.Value, multiple bool) (p *pb.Property, errStr string) { var ( pv pb.PropertyValue unsupported bool ) switch v.Kind() { case reflect.Invalid: // No-op. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: pv.Int64Value = proto.Int64(v.Int()) case reflect.Bool: pv.BooleanValue = proto.Bool(v.Bool()) case reflect.String: pv.StringValue = proto.String(v.String()) case reflect.Float32, reflect.Float64: pv.DoubleValue = proto.Float64(v.Float()) case reflect.Ptr: if k, ok := v.Interface().(*Key); ok { if k != nil { pv.Referencevalue = keyToReferenceValue(defaultAppID, k) } } else { unsupported = true } case reflect.Struct: switch t := v.Interface().(type) { case time.Time: if t.Before(minTime) || t.After(maxTime) { return nil, "time value out of range" } pv.Int64Value = proto.Int64(toUnixMicro(t)) case appengine.GeoPoint: if !t.Valid() { return nil, "invalid GeoPoint value" } // NOTE: Strangely, latitude maps to X, longitude to Y. pv.Pointvalue = &pb.PropertyValue_PointValue{X: &t.Lat, Y: &t.Lng} default: unsupported = true } case reflect.Slice: if b, ok := v.Interface().([]byte); ok { pv.StringValue = proto.String(string(b)) } else { // nvToProto should already catch slice values. // If we get here, we have a slice of slice values. unsupported = true } default: unsupported = true } if unsupported { return nil, "unsupported datastore value type: " + v.Type().String() } p = &pb.Property{ Name: proto.String(name), Value: &pv, Multiple: proto.Bool(multiple), } if v.IsValid() { switch v.Interface().(type) { case []byte: p.Meaning = pb.Property_BLOB.Enum() case ByteString: p.Meaning = pb.Property_BYTESTRING.Enum() case appengine.BlobKey: p.Meaning = pb.Property_BLOBKEY.Enum() case time.Time: p.Meaning = pb.Property_GD_WHEN.Enum() case appengine.GeoPoint: p.Meaning = pb.Property_GEORSS_POINT.Enum() } } return p, "" }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1938-L1942
func (v *ReloadParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage21(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L221-L243
func newPolicyRequirementFromJSON(data []byte) (PolicyRequirement, error) { var typeField prCommon if err := json.Unmarshal(data, &typeField); err != nil { return nil, err } var res PolicyRequirement switch typeField.Type { case prTypeInsecureAcceptAnything: res = &prInsecureAcceptAnything{} case prTypeReject: res = &prReject{} case prTypeSignedBy: res = &prSignedBy{} case prTypeSignedBaseLayer: res = &prSignedBaseLayer{} default: return nil, InvalidPolicyFormatError(fmt.Sprintf("Unknown policy requirement type \"%s\"", typeField.Type)) } if err := json.Unmarshal(data, &res); err != nil { return nil, err } return res, nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L110-L112
func (s *selectable) First(selector string) *Selection { return newSelection(s.session, s.selectors.Append(target.CSS, selector).At(0)) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/config.go#L64-L70
func GetProtoConfig(c *config.Config) *ProtoConfig { pc := c.Exts[protoName] if pc == nil { return nil } return pc.(*ProtoConfig) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/pbutil/pbutil.go#L54-L60
func (r *readWriter) Read(val proto.Message) error { buf, err := r.ReadBytes() if err != nil { return err } return proto.Unmarshal(buf, val) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L84-L119
func (srv *Server) StartServe() error { var err error srv.ln, err = net.Listen(srv.network, srv.address) if err != nil { return err } var opts []grpc.ServerOption opts = append(opts, grpc.MaxRecvMsgSize(int(maxRequestBytes+grpcOverheadBytes))) opts = append(opts, grpc.MaxSendMsgSize(maxSendBytes)) opts = append(opts, grpc.MaxConcurrentStreams(maxStreams)) srv.grpcServer = grpc.NewServer(opts...) rpcpb.RegisterTransportServer(srv.grpcServer, srv) srv.lg.Info( "gRPC server started", zap.String("address", srv.address), zap.String("listener-address", srv.ln.Addr().String()), ) err = srv.grpcServer.Serve(srv.ln) if err != nil && strings.Contains(err.Error(), "use of closed network connection") { srv.lg.Info( "gRPC server is shut down", zap.String("address", srv.address), zap.Error(err), ) } else { srv.lg.Warn( "gRPC server returned with error", zap.String("address", srv.address), zap.Error(err), ) } return err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L486-L510
func newPolicyReferenceMatchFromJSON(data []byte) (PolicyReferenceMatch, error) { var typeField prmCommon if err := json.Unmarshal(data, &typeField); err != nil { return nil, err } var res PolicyReferenceMatch switch typeField.Type { case prmTypeMatchExact: res = &prmMatchExact{} case prmTypeMatchRepoDigestOrExact: res = &prmMatchRepoDigestOrExact{} case prmTypeMatchRepository: res = &prmMatchRepository{} case prmTypeExactReference: res = &prmExactReference{} case prmTypeExactRepository: res = &prmExactRepository{} default: return nil, InvalidPolicyFormatError(fmt.Sprintf("Unknown policy reference match type \"%s\"", typeField.Type)) } if err := json.Unmarshal(data, &res); err != nil { return nil, err } return res, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2474-L2478
func (v GetPropertiesReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime21(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcnotify/tcnotify.go#L169-L173
func (notify *Notify) AddDenylistAddress(payload *NotificationTypeAndAddress) error { cd := tcclient.Client(*notify) _, _, err := (&cd).APICall(payload, "POST", "/denylist/add", nil, nil) return err }
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/perm.go#L4-L23
func Permutations(list Replacer, select_num int, repeatable bool, buf int) (c chan Replacer) { c = make(chan Replacer, buf) go func() { defer close(c) var perm_generator func([]int, int, int) chan []int if repeatable { perm_generator = repeated_permutations } else { perm_generator = permutations } indices := make([]int, list.Len(), list.Len()) for i := 0; i < list.Len(); i++ { indices[i] = i } for perm := range perm_generator(indices, select_num, buf) { c <- list.Replace(perm) } }() return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1224-L1228
func (v *GetHistogramsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser12(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry_interceptor.go#L102-L131
func (c *Client) streamClientInterceptor(logger *zap.Logger, optFuncs ...retryOption) grpc.StreamClientInterceptor { intOpts := reuseOrNewWithCallOptions(defaultOptions, optFuncs) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { grpcOpts, retryOpts := filterCallOptions(opts) callOpts := reuseOrNewWithCallOptions(intOpts, retryOpts) // short circuit for simplicity, and avoiding allocations. if callOpts.max == 0 { return streamer(ctx, desc, cc, method, grpcOpts...) } if desc.ClientStreams { return nil, grpc.Errorf(codes.Unimplemented, "clientv3/retry_interceptor: cannot retry on ClientStreams, set Disable()") } newStreamer, err := streamer(ctx, desc, cc, method, grpcOpts...) logger.Warn("retry stream intercept", zap.Error(err)) if err != nil { // TODO(mwitkow): Maybe dial and transport errors should be retriable? return nil, err } retryingStreamer := &serverStreamingRetryingStream{ client: c, ClientStream: newStreamer, callOpts: callOpts, ctx: ctx, streamerCall: func(ctx context.Context) (grpc.ClientStream, error) { return streamer(ctx, desc, cc, method, grpcOpts...) }, } return retryingStreamer, nil } }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L967-L969
func (g *Glg) Error(val ...interface{}) error { return g.out(ERR, blankFormat(len(val)), val...) }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L222-L233
func (p *Pact) Teardown() *Pact { log.Println("[DEBUG] teardown") if p.Server != nil { server, err := p.pactClient.StopServer(p.Server) if err != nil { log.Println("error:", err) } p.Server = server } return p }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L2004-L2019
func (v *VM) SetMemorySize(size uint) error { if size == 0 { size = 4 } // Makes sure memory size is divisible by 4, otherwise VMware is going to // silently fail, cancelling vix operations. if size%4 != 0 { size = uint(math.Floor(float64((size / 4) * 4))) } return v.updateVMX(func(model *vmx.VirtualMachine) error { model.Memsize = size return nil }) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L274-L276
func (u AccountId) ArmForSwitch(sw int32) (string, bool) { return PublicKey(u).ArmForSwitch(sw) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L249-L252
func (p SetDeviceMetricsOverrideParams) WithDontSetVisibleSize(dontSetVisibleSize bool) *SetDeviceMetricsOverrideParams { p.DontSetVisibleSize = dontSetVisibleSize return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1479-L1483
func (v SetBreakpointByURLParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger15(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1028-L1032
func (v *RemoteObject) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime9(&r, v) return r.Error() }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L565-L567
func (g *Glg) HTTPLogger(name string, handler http.Handler) http.Handler { return g.HTTPLoggerFunc(name, handler.ServeHTTP) }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/buffalo/cmd/fix/webpack.go#L17-L69
func WebpackCheck(r *Runner) error { fmt.Println("~~~ Checking webpack.config.js ~~~") if !r.App.WithWebpack { return nil } box := webpack.Templates f, err := box.FindString("webpack.config.js.tmpl") if err != nil { return err } tmpl, err := template.New("webpack").Parse(f) if err != nil { return err } bb := &bytes.Buffer{} err = tmpl.Execute(bb, map[string]interface{}{ "opts": &webpack.Options{ App: r.App, }, }) if err != nil { return err } b, err := ioutil.ReadFile("webpack.config.js") if err != nil { return err } if string(b) == bb.String() { return nil } if !ask("Your webpack.config.js file is different from the latest Buffalo template.\nWould you like to replace yours with the latest template?") { fmt.Println("\tSkipping webpack.config.js") return nil } wf, err := os.Create("webpack.config.js") if err != nil { return err } _, err = wf.Write(bb.Bytes()) if err != nil { return err } return wf.Close() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_builder.go#L170-L176
func (cb *ContextBuilder) SetTimeoutPerAttempt(timeoutPerAttempt time.Duration) *ContextBuilder { if cb.RetryOptions == nil { cb.RetryOptions = &RetryOptions{} } cb.RetryOptions.TimeoutPerAttempt = timeoutPerAttempt return cb }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L459-L463
func (v *SetScrollbarsHiddenParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation4(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L5114-L5118
func (v *CallFunctionOnParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime47(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/config.go#L77-L93
func upsertConfig(tx *sql.Tx, table string, values map[string]string) error { if len(values) == 0 { return nil // Nothing to update } query := fmt.Sprintf("INSERT OR REPLACE INTO %s (key, value) VALUES", table) exprs := []string{} params := []interface{}{} for key, value := range values { exprs = append(exprs, "(?, ?)") params = append(params, key) params = append(params, value) } query += strings.Join(exprs, ",") _, err := tx.Exec(query, params...) return err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_transport.go#L146-L148
func (ref ociArchiveReference) DeleteImage(ctx context.Context, sys *types.SystemContext) error { return errors.Errorf("Deleting images not implemented for oci: images") }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon_images.go#L81-L599
func (d *Daemon) ImageDownload(op *operation, server string, protocol string, certificate string, secret string, alias string, forContainer bool, autoUpdate bool, storagePool string, preferCached bool, project string) (*api.Image, error) { var err error var ctxMap log.Ctx var remote lxd.ImageServer var info *api.Image // Default protocol is LXD if protocol == "" { protocol = "lxd" } // Default the fingerprint to the alias string we received fp := alias // Attempt to resolve the alias if protocol == "simplestreams" { imageStreamCacheLock.Lock() imageStreamCache, err := imageGetStreamCache(d) if err != nil { imageStreamCacheLock.Unlock() return nil, err } entry, _ := imageStreamCache[server] if entry == nil || entry.Expiry.Before(time.Now()) { // Add a new entry to the cache refresh := func() (*imageStreamCacheEntry, error) { // Setup simplestreams client remote, err = lxd.ConnectSimpleStreams(server, &lxd.ConnectionArgs{ TLSServerCert: certificate, UserAgent: version.UserAgent, Proxy: d.proxy, }) if err != nil { return nil, err } // Get all aliases aliases, err := remote.GetImageAliases() if err != nil { return nil, err } // Get all fingerprints images, err := remote.GetImages() if err != nil { return nil, err } fingerprints := []string{} for _, image := range images { fingerprints = append(fingerprints, image.Fingerprint) } // Generate cache entry entry = &imageStreamCacheEntry{Aliases: aliases, Certificate: certificate, Fingerprints: fingerprints, Expiry: time.Now().Add(time.Hour)} imageStreamCache[server] = entry imageSaveStreamCache(d.os, imageStreamCache) return entry, nil } newEntry, err := refresh() if err == nil { // Cache refreshed entry = newEntry } else if entry != nil { // Failed to fetch entry but existing cache logger.Warn("Unable to refresh cache, using stale entry", log.Ctx{"server": server}) entry.Expiry = time.Now().Add(time.Hour) } else { // Failed to fetch entry and nothing in cache imageStreamCacheLock.Unlock() return nil, err } } else { // use the existing entry logger.Debug("Using SimpleStreams cache entry", log.Ctx{"server": server, "expiry": entry.Expiry}) remote, err = lxd.ConnectSimpleStreams(server, &lxd.ConnectionArgs{ TLSServerCert: entry.Certificate, UserAgent: version.UserAgent, Proxy: d.proxy, }) if err != nil { imageStreamCacheLock.Unlock() return nil, err } } imageStreamCacheLock.Unlock() // Look for a matching alias for _, entry := range entry.Aliases { if entry.Name != fp { continue } fp = entry.Target break } // Expand partial fingerprints matches := []string{} for _, entry := range entry.Fingerprints { if strings.HasPrefix(entry, fp) { matches = append(matches, entry) } } if len(matches) == 1 { fp = matches[0] } else if len(matches) > 1 { return nil, fmt.Errorf("Provided partial image fingerprint matches more than one image") } else { return nil, fmt.Errorf("The requested image couldn't be found") } } else if protocol == "lxd" { // Setup LXD client remote, err = lxd.ConnectPublicLXD(server, &lxd.ConnectionArgs{ TLSServerCert: certificate, UserAgent: version.UserAgent, Proxy: d.proxy, }) if err != nil { return nil, err } // For public images, handle aliases and initial metadata if secret == "" { // Look for a matching alias entry, _, err := remote.GetImageAlias(fp) if err == nil { fp = entry.Target } // Expand partial fingerprints info, _, err = remote.GetImage(fp) if err != nil { return nil, err } fp = info.Fingerprint } } // If auto-update is on and we're being given the image by // alias, try to use a locally cached image matching the given // server/protocol/alias, regardless of whether it's stale or // not (we can assume that it will be not *too* stale since // auto-update is on). interval, err := cluster.ConfigGetInt64(d.cluster, "images.auto_update_interval") if err != nil { return nil, err } if preferCached && interval > 0 && alias != fp { cachedFingerprint, err := d.cluster.ImageSourceGetCachedFingerprint(server, protocol, alias) if err == nil && cachedFingerprint != fp { fp = cachedFingerprint } } // Check if the image already exists in this project (partial hash match) _, imgInfo, err := d.cluster.ImageGet(project, fp, false, true) if err == db.ErrNoSuchObject { // Check if the image already exists in some other project. _, imgInfo, err = d.cluster.ImageGetFromAnyProject(fp) if err == nil { // We just need to insert the database data, no actual download necessary. err = d.cluster.ImageInsert( project, imgInfo.Fingerprint, imgInfo.Filename, imgInfo.Size, false, imgInfo.AutoUpdate, imgInfo.Architecture, imgInfo.CreatedAt, imgInfo.ExpiresAt, imgInfo.Properties) if err != nil { return nil, err } var id int id, imgInfo, err = d.cluster.ImageGet(project, fp, false, true) if err != nil { return nil, err } err = d.cluster.ImageSourceInsert(id, server, protocol, certificate, alias) if err != nil { return nil, err } } } if err == nil { logger.Debug("Image already exists in the db", log.Ctx{"image": fp}) info = imgInfo // If not requested in a particular pool, we're done. if storagePool == "" { return info, nil } // Get the ID of the target storage pool poolID, err := d.cluster.StoragePoolGetID(storagePool) if err != nil { return nil, err } // Check if the image is already in the pool poolIDs, err := d.cluster.ImageGetPools(info.Fingerprint) if err != nil { return nil, err } if shared.Int64InSlice(poolID, poolIDs) { logger.Debugf("Image already exists on storage pool \"%s\"", storagePool) return info, nil } // Import the image in the pool logger.Debugf("Image does not exist on storage pool \"%s\"", storagePool) err = imageCreateInPool(d, info, storagePool) if err != nil { logger.Debugf("Failed to create image on storage pool \"%s\": %s", storagePool, err) return nil, err } logger.Debugf("Created image on storage pool \"%s\"", storagePool) return info, nil } // Deal with parallel downloads imagesDownloadingLock.Lock() if waitChannel, ok := imagesDownloading[fp]; ok { // We are already downloading the image imagesDownloadingLock.Unlock() logger.Debug( "Already downloading the image, waiting for it to succeed", log.Ctx{"image": fp}) // Wait until the download finishes (channel closes) <-waitChannel // Grab the database entry _, imgInfo, err := d.cluster.ImageGet(project, fp, false, true) if err != nil { // Other download failed, lets try again logger.Error("Other image download didn't succeed", log.Ctx{"image": fp}) } else { // Other download succeeded, we're done return imgInfo, nil } } else { imagesDownloadingLock.Unlock() } // Add the download to the queue imagesDownloadingLock.Lock() imagesDownloading[fp] = make(chan bool) imagesDownloadingLock.Unlock() // Unlock once this func ends. defer func() { imagesDownloadingLock.Lock() if waitChannel, ok := imagesDownloading[fp]; ok { close(waitChannel) delete(imagesDownloading, fp) } imagesDownloadingLock.Unlock() }() // Begin downloading if op == nil { ctxMap = log.Ctx{"alias": alias, "server": server} } else { ctxMap = log.Ctx{"trigger": op.url, "image": fp, "operation": op.id, "alias": alias, "server": server} } logger.Info("Downloading image", ctxMap) // Cleanup any leftover from a past attempt destDir := shared.VarPath("images") destName := filepath.Join(destDir, fp) failure := true cleanup := func() { if failure { os.Remove(destName) os.Remove(destName + ".rootfs") } } defer cleanup() // Setup a progress handler progress := func(progress ioprogress.ProgressData) { if op == nil { return } meta := op.metadata if meta == nil { meta = make(map[string]interface{}) } if meta["download_progress"] != progress.Text { meta["download_progress"] = progress.Text op.UpdateMetadata(meta) } } var canceler *cancel.Canceler if op != nil { canceler = cancel.NewCanceler() op.canceler = canceler } if protocol == "lxd" || protocol == "simplestreams" { // Create the target files dest, err := os.Create(destName) if err != nil { return nil, err } defer dest.Close() destRootfs, err := os.Create(destName + ".rootfs") if err != nil { return nil, err } defer destRootfs.Close() // Get the image information if info == nil { if secret != "" { info, _, err = remote.GetPrivateImage(fp, secret) if err != nil { return nil, err } // Expand the fingerprint now and mark alias string to match fp = info.Fingerprint alias = info.Fingerprint } else { info, _, err = remote.GetImage(fp) if err != nil { return nil, err } } } // Download the image var resp *lxd.ImageFileResponse request := lxd.ImageFileRequest{ MetaFile: io.WriteSeeker(dest), RootfsFile: io.WriteSeeker(destRootfs), ProgressHandler: progress, Canceler: canceler, DeltaSourceRetriever: func(fingerprint string, file string) string { path := shared.VarPath("images", fmt.Sprintf("%s.%s", fingerprint, file)) if shared.PathExists(path) { return path } return "" }, } if secret != "" { resp, err = remote.GetPrivateImageFile(fp, secret, request) } else { resp, err = remote.GetImageFile(fp, request) } if err != nil { return nil, err } // Deal with unified images if resp.RootfsSize == 0 { err := os.Remove(destName + ".rootfs") if err != nil { return nil, err } } } else if protocol == "direct" { // Setup HTTP client httpClient, err := util.HTTPClient(certificate, d.proxy) if err != nil { return nil, err } req, err := http.NewRequest("GET", server, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", version.UserAgent) // Make the request raw, doneCh, err := cancel.CancelableDownload(canceler, httpClient, req) defer close(doneCh) if err != nil { return nil, err } if raw.StatusCode != http.StatusOK { return nil, fmt.Errorf("Unable to fetch %s: %s", server, raw.Status) } // Progress handler body := &ioprogress.ProgressReader{ ReadCloser: raw.Body, Tracker: &ioprogress.ProgressTracker{ Length: raw.ContentLength, Handler: func(percent int64, speed int64) { progress(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))}) }, }, } // Create the target files f, err := os.Create(destName) if err != nil { return nil, err } defer f.Close() // Hashing sha256 := sha256.New() // Download the image size, err := io.Copy(io.MultiWriter(f, sha256), body) if err != nil { return nil, err } // Validate hash result := fmt.Sprintf("%x", sha256.Sum(nil)) if result != fp { return nil, fmt.Errorf("Hash mismatch for %s: %s != %s", server, result, fp) } // Parse the image imageMeta, err := getImageMetadata(destName) if err != nil { return nil, err } info = &api.Image{} info.Fingerprint = fp info.Size = size info.Architecture = imageMeta.Architecture info.CreatedAt = time.Unix(imageMeta.CreationDate, 0) info.ExpiresAt = time.Unix(imageMeta.ExpiryDate, 0) info.Properties = imageMeta.Properties } // Override visiblity info.Public = false // We want to enable auto-update only if we were passed an // alias name, so we can figure when the associated // fingerprint changes in the remote. if alias != fp { info.AutoUpdate = autoUpdate } // Create the database entry err = d.cluster.ImageInsert(project, info.Fingerprint, info.Filename, info.Size, info.Public, info.AutoUpdate, info.Architecture, info.CreatedAt, info.ExpiresAt, info.Properties) if err != nil { return nil, err } // Image is in the DB now, don't wipe on-disk files on failure failure = false // Check if the image path changed (private images) newDestName := filepath.Join(destDir, fp) if newDestName != destName { err = shared.FileMove(destName, newDestName) if err != nil { return nil, err } if shared.PathExists(destName + ".rootfs") { err = shared.FileMove(destName+".rootfs", newDestName+".rootfs") if err != nil { return nil, err } } } // Record the image source if alias != fp { id, _, err := d.cluster.ImageGet(project, fp, false, true) if err != nil { return nil, err } err = d.cluster.ImageSourceInsert(id, server, protocol, certificate, alias) if err != nil { return nil, err } } // Import into the requested storage pool if storagePool != "" { err = imageCreateInPool(d, info, storagePool) if err != nil { return nil, err } } // Mark the image as "cached" if downloading for a container if forContainer { err := d.cluster.ImageLastAccessInit(fp) if err != nil { return nil, err } } logger.Info("Image downloaded", ctxMap) return info, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L411-L414
func (p SynthesizePinchGestureParams) WithRelativeSpeed(relativeSpeed int64) *SynthesizePinchGestureParams { p.RelativeSpeed = relativeSpeed return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L261-L265
func (v TakeCoverageDeltaParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/webhook.go#L26-L46
func webhookList(w http.ResponseWriter, r *http.Request, t auth.Token) error { ctxs := permission.ContextsForPermission(t, permission.PermWebhookRead, permTypes.CtxTeam) var teams []string for _, c := range ctxs { if c.CtxType == permTypes.CtxGlobal { teams = nil break } teams = append(teams, c.Value) } webhooks, err := servicemanager.Webhook.List(teams) if err != nil { return err } if len(webhooks) == 0 { w.WriteHeader(http.StatusNoContent) return nil } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(webhooks) }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L148-L150
func (mux *LoggingServeMux) Handler(r *http.Request) (h http.Handler, pattern string) { return mux.serveMux.Handler(r) }
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/api.go#L154-L160
func (da *Cedar) Get(key []byte) (value int, err error) { to, err := da.Jump(key, 0) if err != nil { return 0, err } return da.Value(to) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1303-L1307
func (v *GetHistogramReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser13(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2500-L2504
func (v RuleUsage) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss23(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L40-L47
func newLoggingPipe() *loggingPipe { p := &loggingPipe{} p.clientReader, p.clientWriter = io.Pipe() p.clientReader = io.TeeReader(p.clientReader, &p.ServerToClientBuf) p.serverReader, p.serverWriter = io.Pipe() p.serverReader = io.TeeReader(p.serverReader, &p.ClientToServerBuf) return p }