_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/request.go#L107-L148
func (r *Request) GetCorsInfo() *CorsInfo { origin := r.Header.Get("Origin") var originUrl *url.URL var isCors bool if origin == "" { isCors = false } else if origin == "null" { isCors = true } else { var err error originUrl, err = url.ParseRequestURI(origin) isCors = err == nil && r.Host != originUrl.Host } reqMethod := r.Header.Get("Access-Control-Request-Method") reqHeaders := []string{} rawReqHeaders := r.Header[http.CanonicalHeaderKey("Access-Control-Request-Headers")] for _, rawReqHeader := range rawReqHeaders { if len(rawReqHeader) == 0 { continue } // net/http does not handle comma delimited headers for us for _, reqHeader := range strings.Split(rawReqHeader, ",") { reqHeaders = append(reqHeaders, http.CanonicalHeaderKey(strings.TrimSpace(reqHeader))) } } isPreflight := isCors && r.Method == "OPTIONS" && reqMethod != "" return &CorsInfo{ IsCors: isCors, IsPreflight: isPreflight, Origin: origin, OriginUrl: originUrl, AccessControlRequestMethod: strings.ToUpper(reqMethod), AccessControlRequestHeaders: reqHeaders, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/stats/metrickey.go#L77-L87
func writeClean(buf *bytes.Buffer, v string) { for i := 0; i < len(v); i++ { c := v[i] switch c { case '{', '}', '/', '\\', ':', '.', ' ', '\t', '\r', '\n': buf.WriteByte('-') default: buf.WriteByte(c) } } }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/cause.go#L16-L35
func Cause(err Error) error { attributes := err.Attributes() if attributes == nil { return nil } cause, ok := attributes[causeKey] if !ok { return nil } switch v := cause.(type) { case error: return v case string: return errors.New(v) default: return nil } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux_cgo.go#L358-L404
func GroupId(name string) (int, error) { var grp C.struct_group var result *C.struct_group bufSize := C.sysconf(C._SC_GETGR_R_SIZE_MAX) if bufSize < 0 { bufSize = 4096 } buf := C.malloc(C.size_t(bufSize)) if buf == nil { return -1, fmt.Errorf("allocation failed") } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) again: rv, errno := C.getgrnam_r(cname, &grp, (*C.char)(buf), C.size_t(bufSize), &result) if rv != 0 { // OOM killer will take care of us if we end up doing this too // often. if errno == syscall.ERANGE { bufSize *= 2 tmp := C.realloc(buf, C.size_t(bufSize)) if tmp == nil { return -1, fmt.Errorf("allocation failed") } buf = tmp goto again } C.free(buf) return -1, fmt.Errorf("failed group lookup: %s", syscall.Errno(rv)) } C.free(buf) if result == nil { return -1, fmt.Errorf("unknown group %s", name) } return int(C.int(result.gr_gid)), nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dwarf.go#L346-L394
func (p *Process) readRuntimeConstants() { p.rtConstants = map[string]int64{} // Hardcoded values for Go 1.9. // (Go did not have constants in DWARF before 1.10.) m := p.rtConstants m["_MSpanDead"] = 0 m["_MSpanInUse"] = 1 m["_MSpanManual"] = 2 m["_MSpanFree"] = 3 m["_Gidle"] = 0 m["_Grunnable"] = 1 m["_Grunning"] = 2 m["_Gsyscall"] = 3 m["_Gwaiting"] = 4 m["_Gdead"] = 6 m["_Gscan"] = 0x1000 m["_PCDATA_StackMapIndex"] = 0 m["_FUNCDATA_LocalsPointerMaps"] = 1 m["_FUNCDATA_ArgsPointerMaps"] = 0 m["tflagExtraStar"] = 1 << 1 m["kindGCProg"] = 1 << 6 m["kindDirectIface"] = 1 << 5 m["_PageSize"] = 1 << 13 m["_KindSpecialFinalizer"] = 1 // From 1.10, these constants are recorded in DWARF records. d, _ := p.proc.DWARF() r := d.Reader() for e, err := r.Next(); e != nil && err == nil; e, err = r.Next() { if e.Tag != dwarf.TagConstant { continue } f := e.AttrField(dwarf.AttrName) if f == nil { continue } name := f.Val.(string) if !strings.HasPrefix(name, "runtime.") { continue } name = name[8:] c := e.AttrField(dwarf.AttrConstValue) if c == nil { continue } p.rtConstants[name] = c.Val.(int64) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L1648-L1652
func (v Layer) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree14(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L302-L323
func decodePeers(buf []byte, trans Transport) Configuration { // Decode the buffer first. var encPeers [][]byte if err := decodeMsgPack(buf, &encPeers); err != nil { panic(fmt.Errorf("failed to decode peers: %v", err)) } // Deserialize each peer. var servers []Server for _, enc := range encPeers { p := trans.DecodePeer(enc) servers = append(servers, Server{ Suffrage: Voter, ID: ServerID(p), Address: ServerAddress(p), }) } return Configuration{ Servers: servers, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api.go#L18-L47
func RestServer(d *Daemon) *http.Server { /* Setup the web server */ mux := mux.NewRouter() mux.StrictSlash(false) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") SyncResponse(true, []string{"/1.0"}).Render(w) }) for endpoint, f := range d.gateway.HandlerFuncs() { mux.HandleFunc(endpoint, f) } for _, c := range api10 { d.createCmd(mux, "1.0", c) } for _, c := range apiInternal { d.createCmd(mux, "internal", c) } mux.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { logger.Info("Sending top level 404", log.Ctx{"url": r.URL}) w.Header().Set("Content-Type", "application/json") NotFound(nil).Render(w) }) return &http.Server{Handler: &lxdHttpServer{r: mux, d: d}} }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L123-L127
func RightF(n int) func(string) string { return func(s string) string { return Right(s, n) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L317-L319
func (d *Daemon) State() *state.State { return state.NewState(d.db, d.cluster, d.maas, d.os, d.endpoints) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/cov/util.go#L27-L42
func DumpProfile(profiles []*cover.Profile, writer io.Writer) error { if len(profiles) == 0 { return errors.New("can't write an empty profile") } if _, err := io.WriteString(writer, "mode: "+profiles[0].Mode+"\n"); err != nil { return err } for _, profile := range profiles { for _, block := range profile.Blocks { if _, err := fmt.Fprintf(writer, "%s:%d.%d,%d.%d %d %d\n", profile.FileName, block.StartLine, block.StartCol, block.EndLine, block.EndCol, block.NumStmt, block.Count); err != nil { return err } } } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/prowjob.go#L100-L109
func (c *prowJobs) Create(prowJob *v1.ProwJob) (result *v1.ProwJob, err error) { result = &v1.ProwJob{} err = c.client.Post(). Namespace(c.ns). Resource("prowjobs"). Body(prowJob). Do(). Into(result) return }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/integers.go#L117-L165
func (b *TupleBuilder) PutInt16(field string, value int16) (wrote uint64, err error) { // field type should be if err = b.typeCheck(field, Int16Field); err != nil { return 0, err } if uint16(value) < math.MaxUint8 { // minimum bytes is 2 (type code + value) if b.available() < 2 { return 0, xbinary.ErrOutOfRange } // write type code b.buffer[b.pos] = byte(Short8Code.OpCode) // write value b.buffer[b.pos+1] = byte(value) // set field offset b.offsets[field] = b.pos // incr pos b.pos += 2 return 2, nil } // write value // length check performed by xbinary wrote, err = xbinary.LittleEndian.PutInt16(b.buffer, b.pos+1, value) if err != nil { return 0, err } // write type code b.buffer[b.pos] = byte(Short16Code.OpCode) // set field offset b.offsets[field] = b.pos // incr pos b.pos += 3 // wrote 3 bytes return 3, nil }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/format/format.go#L375-L382
func isPrintableString(str string) bool { for _, runeValue := range str { if !strconv.IsPrint(runeValue) { return false } } return true }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/sync/sync.go#L284-L312
func (p *Puller) PullTree(client *pachclient.APIClient, root string, tree hashtree.HashTree, pipes bool, concurrency int) error { limiter := limit.New(concurrency) var eg errgroup.Group if err := tree.Walk("/", func(path string, node *hashtree.NodeProto) error { if node.FileNode != nil { path := filepath.Join(root, path) var hashes []string for _, object := range node.FileNode.Objects { hashes = append(hashes, object.Hash) } if pipes { return p.makePipe(path, func(w io.Writer) error { return client.GetObjects(hashes, 0, 0, uint64(node.SubtreeSize), w) }) } limiter.Acquire() eg.Go(func() (retErr error) { defer limiter.Release() return p.makeFile(path, func(w io.Writer) error { return client.GetObjects(hashes, 0, 0, uint64(node.SubtreeSize), w) }) }) } return nil }); err != nil { return err } return eg.Wait() }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L29-L35
func getTypeFromPointer(ptr interface{}) reflect.Type { rt := reflect.TypeOf(ptr) if rt.Kind() != reflect.Ptr { panic(fmt.Sprintf("expected pointer, got %v", rt)) } return rt.Elem() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/file.go#L63-L99
func (c *Config) SaveConfig(path string) error { // Create a new copy for the config file conf := Config{} err := shared.DeepCopy(c, &conf) if err != nil { return fmt.Errorf("Unable to copy the configuration: %v", err) } // Remove the static remotes for k := range StaticRemotes { if k == "local" { continue } delete(conf.Remotes, k) } // Create the config file (or truncate an existing one) f, err := os.Create(path) if err != nil { return fmt.Errorf("Unable to create the configuration file: %v", err) } defer f.Close() // Write the new config data, err := yaml.Marshal(conf) if err != nil { return fmt.Errorf("Unable to marshal the configuration: %v", err) } _, err = f.Write(data) if err != nil { return fmt.Errorf("Unable to write the configuration: %v", err) } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay_timer_pool.go#L66-L85
func (tp *relayTimerPool) Get() *relayTimer { timer, ok := tp.pool.Get().(*relayTimer) if ok { timer.released = false return timer } rt := &relayTimer{ pool: tp, } // Go timers are started by default. However, we need to separate creating // the timer and starting the timer for use in the relay code paths. // To make this work without more locks in the relayTimer, we create a Go timer // with a huge timeout so it doesn't run, then stop it so we can start it later. rt.timer = time.AfterFunc(time.Duration(math.MaxInt64), rt.OnTimer) if !rt.timer.Stop() { panic("relayTimer requires timers in stopped state, but failed to stop underlying timer") } return rt }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L536-L553
func (c *Cluster) ContainerProjectAndName(id int) (string, string, error) { q := ` SELECT projects.name, containers.name FROM containers JOIN projects ON projects.id = containers.project_id WHERE containers.id=? ` project := "" name := "" arg1 := []interface{}{id} arg2 := []interface{}{&project, &name} err := dbQueryRowScan(c.db, q, arg1, arg2) if err == sql.ErrNoRows { return "", "", ErrNoSuchObject } return project, name, err }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L310-L333
func (p *Part) Clone(parent *Part) *Part { if p == nil { return nil } newPart := &Part{ PartID: p.PartID, Header: p.Header, Parent: parent, Boundary: p.Boundary, ContentID: p.ContentID, ContentType: p.ContentType, Disposition: p.Disposition, FileName: p.FileName, Charset: p.Charset, Errors: p.Errors, Content: p.Content, Epilogue: p.Epilogue, } newPart.FirstChild = p.FirstChild.Clone(newPart) newPart.NextSibling = p.NextSibling.Clone(parent) return newPart }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L174-L212
func (w *BatchingWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error { log := w.log.WithField("config", bpConf) w.pointChanMutex.RLock() ch, ok := w.pointChans[bpConf] w.pointChanMutex.RUnlock() if !ok { w.pointChanMutex.Lock() ch, ok = w.pointChans[bpConf] if !ok { w.mutex.Lock() w.active++ w.limit++ w.mutex.Unlock() ch = make(chan *batchPoint) w.pointChans[bpConf] = ch go writeInBatches(log, w.writer, bpConf, w.scalingInterval, ch, true) } w.pointChanMutex.Unlock() } point := &batchPoint{ Point: p, errch: make(chan error, 1), } select { case ch <- point: case <-time.After(w.scalingInterval): w.mutex.Lock() if w.active < w.limit { w.active++ go writeInBatches(w.log, w.writer, bpConf, w.scalingInterval, ch, false) } w.mutex.Unlock() ch <- point } return <-point.errch }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L24-L58
func (d *APIDescriptor) Merge(other *APIDescriptor) error { if d.Version != other.Version { return fmt.Errorf("Can't merge API descriptors with different versions") } for _, name := range d.ResourceNames { for _, otherName := range other.ResourceNames { if name == otherName { return fmt.Errorf("%s is a resource that exists in multiple APIs, generate separate clients", name) } } } for _, name := range d.TypeNames { for i, otherName := range other.TypeNames { if name == otherName { newName := MakeUniq(otherName, append(d.TypeNames, other.TypeNames...)) first := other.TypeNames[:i] last := append([]string{newName}, other.TypeNames[i+1:]...) other.TypeNames = append(first, last...) typ := other.Types[name] delete(other.Types, name) typ.TypeName = newName other.Types[newName] = typ } } } for name, resource := range other.Resources { d.Resources[name] = resource } for name, typ := range other.Types { d.Types[name] = typ } d.ResourceNames = append(d.ResourceNames, other.ResourceNames...) d.TypeNames = append(d.TypeNames, other.TypeNames...) return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/provision.go#L621-L627
func Get(name string) (Provisioner, error) { pFunc, ok := provisioners[name] if !ok { return nil, errors.Errorf("unknown provisioner: %q", name) } return pFunc() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L259-L279
func StorageVolumeConfigAdd(tx *sql.Tx, volumeID int64, volumeConfig map[string]string) error { str := "INSERT INTO storage_volumes_config (storage_volume_id, key, value) VALUES(?, ?, ?)" stmt, err := tx.Prepare(str) defer stmt.Close() if err != nil { return err } for k, v := range volumeConfig { if v == "" { continue } _, err = stmt.Exec(volumeID, k, v) if err != nil { return err } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1342-L1346
func (v NameValuePair) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L249-L252
func (c *ClusterTx) OperationsUUIDs() ([]string, error) { stmt := "SELECT uuid FROM operations WHERE node_id=?" return query.SelectStrings(c.tx, stmt, c.nodeID) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L108-L117
func Open(name string) (*Index, error) { if !validIndexNameOrDocID(name) { return nil, fmt.Errorf("search: invalid index name %q", name) } return &Index{ spec: pb.IndexSpec{ Name: &name, }, }, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L503-L524
func (c *Cluster) StoragePoolConfigGet(poolID int64) (map[string]string, error) { var key, value string query := "SELECT key, value FROM storage_pools_config WHERE storage_pool_id=? AND (node_id=? OR node_id IS NULL)" inargs := []interface{}{poolID, c.nodeID} outargs := []interface{}{key, value} results, err := queryScan(c.db, query, inargs, outargs) if err != nil { return nil, err } config := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) config[key] = value } return config, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2174-L2178
func (v *GlobalLexicalScopeNamesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime19(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/accessibility.go#L136-L145
func (p *GetFullAXTreeParams) Do(ctx context.Context) (nodes []*Node, err error) { // execute var res GetFullAXTreeReturns err = cdp.Execute(ctx, CommandGetFullAXTree, nil, &res) if err != nil { return nil, err } return res.Nodes, nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L650-L681
func protoFileInfo(path_ string, protoInfo proto.FileInfo) fileInfo { info := fileNameInfo(path_) // Look for "option go_package". If there's no / in the package option, then // it's just a simple package name, not a full import path. for _, opt := range protoInfo.Options { if opt.Key != "go_package" { continue } if strings.LastIndexByte(opt.Value, '/') == -1 { info.packageName = opt.Value } else { if i := strings.LastIndexByte(opt.Value, ';'); i != -1 { info.importPath = opt.Value[:i] info.packageName = opt.Value[i+1:] } else { info.importPath = opt.Value info.packageName = path.Base(opt.Value) } } } // Set the Go package name from the proto package name if there was no // option go_package. if info.packageName == "" && protoInfo.PackageName != "" { info.packageName = strings.Replace(protoInfo.PackageName, ".", "_", -1) } info.imports = protoInfo.Imports info.hasServices = protoInfo.HasServices return info }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/types.go#L343-L427
func (t *PropertyName) UnmarshalEasyJSON(in *jlexer.Lexer) { switch PropertyName(in.String()) { case PropertyNameBusy: *t = PropertyNameBusy case PropertyNameDisabled: *t = PropertyNameDisabled case PropertyNameEditable: *t = PropertyNameEditable case PropertyNameFocusable: *t = PropertyNameFocusable case PropertyNameFocused: *t = PropertyNameFocused case PropertyNameHidden: *t = PropertyNameHidden case PropertyNameHiddenRoot: *t = PropertyNameHiddenRoot case PropertyNameInvalid: *t = PropertyNameInvalid case PropertyNameKeyshortcuts: *t = PropertyNameKeyshortcuts case PropertyNameSettable: *t = PropertyNameSettable case PropertyNameRoledescription: *t = PropertyNameRoledescription case PropertyNameLive: *t = PropertyNameLive case PropertyNameAtomic: *t = PropertyNameAtomic case PropertyNameRelevant: *t = PropertyNameRelevant case PropertyNameRoot: *t = PropertyNameRoot case PropertyNameAutocomplete: *t = PropertyNameAutocomplete case PropertyNameHasPopup: *t = PropertyNameHasPopup case PropertyNameLevel: *t = PropertyNameLevel case PropertyNameMultiselectable: *t = PropertyNameMultiselectable case PropertyNameOrientation: *t = PropertyNameOrientation case PropertyNameMultiline: *t = PropertyNameMultiline case PropertyNameReadonly: *t = PropertyNameReadonly case PropertyNameRequired: *t = PropertyNameRequired case PropertyNameValuemin: *t = PropertyNameValuemin case PropertyNameValuemax: *t = PropertyNameValuemax case PropertyNameValuetext: *t = PropertyNameValuetext case PropertyNameChecked: *t = PropertyNameChecked case PropertyNameExpanded: *t = PropertyNameExpanded case PropertyNameModal: *t = PropertyNameModal case PropertyNamePressed: *t = PropertyNamePressed case PropertyNameSelected: *t = PropertyNameSelected case PropertyNameActivedescendant: *t = PropertyNameActivedescendant case PropertyNameControls: *t = PropertyNameControls case PropertyNameDescribedby: *t = PropertyNameDescribedby case PropertyNameDetails: *t = PropertyNameDetails case PropertyNameErrormessage: *t = PropertyNameErrormessage case PropertyNameFlowto: *t = PropertyNameFlowto case PropertyNameLabelledby: *t = PropertyNameLabelledby case PropertyNameOwns: *t = PropertyNameOwns default: in.AddError(errors.New("unknown PropertyName value")) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L214-L227
func (r *ProtocolLXD) UpdateStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshotName string, volume api.StorageVolumeSnapshotPut, ETag string) error { if !r.HasExtension("storage_api_volume_snapshots") { return fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots/%s", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName), url.QueryEscape(snapshotName)) _, _, err := r.queryOperation("PUT", path, volume, ETag) if err != nil { return err } return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/fake/fake_app.go#L108-L116
func (c *FakeApps) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *tsuru_v1.App, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(appsResource, c.ns, name, data, subresources...), &tsuru_v1.App{}) if obj == nil { return nil, err } return obj.(*tsuru_v1.App), err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1116-L1120
func (v PageTimings) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/simplestreams_images.go#L52-L191
func (r *ProtocolSimpleStreams) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) { // Sanity checks if req.MetaFile == nil && req.RootfsFile == nil { return nil, fmt.Errorf("No file requested") } // Attempt to download from host if shared.PathExists("/dev/lxd/sock") && os.Geteuid() == 0 { unixURI := fmt.Sprintf("http://unix.socket/1.0/images/%s/export", url.QueryEscape(fingerprint)) // Setup the HTTP client devlxdHTTP, err := unixHTTPClient(nil, "/dev/lxd/sock") if err == nil { resp, err := lxdDownloadImage(fingerprint, unixURI, r.httpUserAgent, devlxdHTTP, req) if err == nil { return resp, nil } } } // Get the file list files, err := r.ssClient.GetFiles(fingerprint) if err != nil { return nil, err } // Prepare the response resp := ImageFileResponse{} // Download function download := func(path string, filename string, hash string, target io.WriteSeeker) (int64, error) { // Try over http url := fmt.Sprintf("http://%s/%s", strings.TrimPrefix(r.httpHost, "https://"), path) size, err := shared.DownloadFileHash(r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, hash, sha256.New(), target) if err != nil { // Handle cancelation if err.Error() == "net/http: request canceled" { return -1, err } // Try over https url = fmt.Sprintf("%s/%s", r.httpHost, path) size, err = shared.DownloadFileHash(r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, hash, sha256.New(), target) if err != nil { return -1, err } } return size, nil } // Download the LXD image file meta, ok := files["meta"] if ok && req.MetaFile != nil { size, err := download(meta.Path, "metadata", meta.Sha256, req.MetaFile) if err != nil { return nil, err } parts := strings.Split(meta.Path, "/") resp.MetaName = parts[len(parts)-1] resp.MetaSize = size } // Download the rootfs rootfs, ok := files["root"] if ok && req.RootfsFile != nil { // Look for deltas (requires xdelta3) downloaded := false _, err := exec.LookPath("xdelta3") if err == nil && req.DeltaSourceRetriever != nil { for filename, file := range files { if !strings.HasPrefix(filename, "root.delta-") { continue } // Check if we have the source file for the delta srcFingerprint := strings.Split(filename, "root.delta-")[1] srcPath := req.DeltaSourceRetriever(srcFingerprint, "rootfs") if srcPath == "" { continue } // Create temporary file for the delta deltaFile, err := ioutil.TempFile("", "lxc_image_") if err != nil { return nil, err } defer deltaFile.Close() defer os.Remove(deltaFile.Name()) // Download the delta _, err = download(file.Path, "rootfs delta", file.Sha256, deltaFile) if err != nil { return nil, err } // Create temporary file for the delta patchedFile, err := ioutil.TempFile("", "lxc_image_") if err != nil { return nil, err } defer patchedFile.Close() defer os.Remove(patchedFile.Name()) // Apply it _, err = shared.RunCommand("xdelta3", "-f", "-d", "-s", srcPath, deltaFile.Name(), patchedFile.Name()) if err != nil { return nil, err } // Copy to the target size, err := io.Copy(req.RootfsFile, patchedFile) if err != nil { return nil, err } parts := strings.Split(rootfs.Path, "/") resp.RootfsName = parts[len(parts)-1] resp.RootfsSize = size downloaded = true } } // Download the whole file if !downloaded { size, err := download(rootfs.Path, "rootfs", rootfs.Sha256, req.RootfsFile) if err != nil { return nil, err } parts := strings.Split(rootfs.Path, "/") resp.RootfsName = parts[len(parts)-1] resp.RootfsSize = size } } return &resp, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/post_apps_parameters.go#L79-L82
func (o *PostAppsParams) WithTimeout(timeout time.Duration) *PostAppsParams { o.SetTimeout(timeout) return o }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/client/curl.go#L41-L70
func printcURL(req *http.Request) error { if !cURLDebug { return nil } var ( command string b []byte err error ) if req.URL != nil { command = fmt.Sprintf("curl -X %s %s", req.Method, req.URL.String()) } if req.Body != nil { b, err = ioutil.ReadAll(req.Body) if err != nil { return err } command += fmt.Sprintf(" -d %q", string(b)) } fmt.Fprintf(os.Stderr, "cURL Command: %s\n", command) // reset body body := bytes.NewBuffer(b) req.Body = ioutil.NopCloser(body) return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/logutil/package_logger.go#L32-L34
func NewPackageLogger(repo, pkg string) Logger { return &packageLogger{p: capnslog.NewPackageLogger(repo, pkg)} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/ioprogress/writer.go#L14-L25
func (pt *ProgressWriter) Write(p []byte) (int, error) { // Do normal writer tasks n, err := pt.WriteCloser.Write(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2968-L2972
func (v *GetResourceTreeParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage31(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/memory.go#L261-L270
func (p *GetSamplingProfileParams) Do(ctx context.Context) (profile *SamplingProfile, err error) { // execute var res GetSamplingProfileReturns err = cdp.Execute(ctx, CommandGetSamplingProfile, nil, &res) if err != nil { return nil, err } return res.Profile, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L3285-L3287
func (api *API) ScheduledReportLocator(href string) *ScheduledReportLocator { return &ScheduledReportLocator{Href(href), api} }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/commands.go#L37-L39
func (a *API) ShowCommandHelp(cmd string) error { return a.ShowHelp(cmd, "/rll", commandValues) }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/russian/common.go#L55-L75
func findRegions(word *snowballword.SnowballWord) (r1start, r2start, rvstart int) { // R1 & R2 are defined in the standard manner. r1start = romance.VnvSuffix(word, isLowerVowel, 0) r2start = romance.VnvSuffix(word, isLowerVowel, r1start) // Set RV, by default, as empty. rvstart = len(word.RS) // RV is the region after the first vowel, or the end of // the word if it contains no vowel. // for i := 0; i < len(word.RS); i++ { if isLowerVowel(word.RS[i]) { rvstart = i + 1 break } } return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/backoff/exponential.go#L205-L214
func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { var delta = randomizationFactor * float64(currentInterval) var minInterval = float64(currentInterval) - delta var maxInterval = float64(currentInterval) + delta // Get a random value from the range [minInterval, maxInterval]. // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then // we want a 33% chance for selecting either 1, 2 or 3. return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/secp256k1.go#L102-L104
func (k *Secp256k1PublicKey) Raw() ([]byte, error) { return (*btcec.PublicKey)(k).SerializeCompressed(), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L421-L429
func (ap Approvers) UnapprovedFiles() sets.String { unapproved := sets.NewString() for fn, approvers := range ap.GetFilesApprovers() { if len(approvers) == 0 { unapproved.Insert(fn) } } return unapproved }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L217-L220
func (p CreateIsolatedWorldParams) WithWorldName(worldName string) *CreateIsolatedWorldParams { p.WorldName = worldName return &p }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4404-L4407
func (e TransactionResultCode) ValidEnum(v int32) bool { _, ok := transactionResultCodeMap[v] return ok }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_dir.go#L31-L41
func (s *storageDir) StorageCoreInit() error { s.sType = storageTypeDir typeName, err := storageTypeToString(s.sType) if err != nil { return err } s.sTypeName = typeName s.sTypeVersion = "1" return nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L88-L90
func (gc *GraphicContext) StrokeStringAt(text string, x, y float64) (cursor float64) { return gc.drawString(text, stroked, x, y) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L894-L898
func (v ProfileSnapshotParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L312-L322
func (s *FakeTaskManager) NewTask(callerName string, profile taskmanager.ProfileType, status string) (t *taskmanager.Task) { t = new(taskmanager.Task) t.CallerName = callerName t.Profile = profile t.Status = status t.ID = bson.NewObjectId() t.Timestamp = time.Now().UnixNano() t.MetaData = make(map[string]interface{}) t.PrivateMetaData = make(map[string]interface{}) return }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/romance/common.go#L17-L25
func VnvSuffix(word *snowballword.SnowballWord, f isVowelFunc, start int) int { for i := 1; i < len(word.RS[start:]); i++ { j := start + i if f(word.RS[j-1]) && !f(word.RS[j]) { return j + 1 } } return len(word.RS) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/report/weighted.go#L33-L39
func NewWeightedReport(r Report, precision string) Report { return &weightedReport{ baseReport: r, report: newReport(precision), results: make(chan Result, 16), } }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L244-L250
func (p *Page) HTML() (string, error) { html, err := p.session.GetSource() if err != nil { return "", fmt.Errorf("failed to retrieve page HTML: %s", err) } return html, nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L465-L472
func FileSequence_Index(id FileSeqId, frame int) *C.char { fs, ok := sFileSeqs.Get(id) // caller must free string if !ok { return C.CString("") } return C.CString(fs.Index(frame)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/easyjson.go#L213-L217
func (v *GetEncodedResponseParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAudits1(&r, v) return r.Error() }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlnode/xmlnode.go#L32-L43
func (a XMLNode) ResValue() string { switch a.NodeType { case tree.NtAttr: return a.Token.(*xml.Attr).Value case tree.NtChd: return string(a.Token.(xml.CharData)) case tree.NtComm: return string(a.Token.(xml.Comment)) } //case tree.NtPi: return string(a.Token.(xml.ProcInst).Inst) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/easyjson.go#L70-L74
func (v ResolveBlobReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIo(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tethering/easyjson.go#L69-L73
func (v UnbindParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTethering(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/project.go#L71-L77
func (c *Client) SetProjectConfig(projectName string, config ProjectConfig) error { return c.put( []string{"project", projectName, "config"}, config, nil, ) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1474-L1477
func IsGlob(pattern string) bool { pattern = clean(pattern) return globRegex.Match([]byte(pattern)) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/errors.go#L163-L165
func NewSystemError(code SystemErrCode, msg string, args ...interface{}) error { return SystemError{code: code, msg: fmt.Sprintf(msg, args...)} }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L600-L603
func PaddingChars(pad int) *C.char { // caller must free string return C.CString(fileseq.PaddingChars(pad)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1157-L1181
func DashService(opts *AssetOpts) *v1.Service { return &v1.Service{ TypeMeta: metav1.TypeMeta{ Kind: "Service", APIVersion: "v1", }, ObjectMeta: objectMeta(dashName, labels(dashName), nil, opts.Namespace), Spec: v1.ServiceSpec{ Type: v1.ServiceTypeNodePort, Selector: labels(dashName), Ports: []v1.ServicePort{ { Port: 8080, Name: "dash-http", NodePort: 30080, }, { Port: 8081, Name: "grpc-proxy-http", NodePort: 30081, }, }, }, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/fileutil/purge.go#L32-L88
func purgeFile(lg *zap.Logger, dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}, purgec chan<- string) <-chan error { errC := make(chan error, 1) go func() { for { fnames, err := ReadDir(dirname) if err != nil { errC <- err return } newfnames := make([]string, 0) for _, fname := range fnames { if strings.HasSuffix(fname, suffix) { newfnames = append(newfnames, fname) } } sort.Strings(newfnames) fnames = newfnames for len(newfnames) > int(max) { f := filepath.Join(dirname, newfnames[0]) l, err := TryLockFile(f, os.O_WRONLY, PrivateFileMode) if err != nil { break } if err = os.Remove(f); err != nil { errC <- err return } if err = l.Close(); err != nil { if lg != nil { lg.Warn("failed to unlock/close", zap.String("path", l.Name()), zap.Error(err)) } else { plog.Errorf("error unlocking %s when purging file (%v)", l.Name(), err) } errC <- err return } if lg != nil { lg.Info("purged", zap.String("path", f)) } else { plog.Infof("purged file %s successfully", f) } newfnames = newfnames[1:] } if purgec != nil { for i := 0; i < len(fnames)-len(newfnames); i++ { purgec <- fnames[i] } } select { case <-time.After(interval): case <-stop: return } } }() return errC }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/version.go#L70-L80
func (v *DottedVersion) Compare(other *DottedVersion) int { result := compareInts(v.Major, other.Major) if result != 0 { return result } result = compareInts(v.Minor, other.Minor) if result != 0 { return result } return compareInts(v.Patch, other.Patch) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L726-L812
func (r *Raft) restoreUserSnapshot(meta *SnapshotMeta, reader io.Reader) error { defer metrics.MeasureSince([]string{"raft", "restoreUserSnapshot"}, time.Now()) // Sanity check the version. version := meta.Version if version < SnapshotVersionMin || version > SnapshotVersionMax { return fmt.Errorf("unsupported snapshot version %d", version) } // We don't support snapshots while there's a config change // outstanding since the snapshot doesn't have a means to // represent this state. committedIndex := r.configurations.committedIndex latestIndex := r.configurations.latestIndex if committedIndex != latestIndex { return fmt.Errorf("cannot restore snapshot now, wait until the configuration entry at %v has been applied (have applied %v)", latestIndex, committedIndex) } // Cancel any inflight requests. for { e := r.leaderState.inflight.Front() if e == nil { break } e.Value.(*logFuture).respond(ErrAbortedByRestore) r.leaderState.inflight.Remove(e) } // We will overwrite the snapshot metadata with the current term, // an index that's greater than the current index, or the last // index in the snapshot. It's important that we leave a hole in // the index so we know there's nothing in the Raft log there and // replication will fault and send the snapshot. term := r.getCurrentTerm() lastIndex := r.getLastIndex() if meta.Index > lastIndex { lastIndex = meta.Index } lastIndex++ // Dump the snapshot. Note that we use the latest configuration, // not the one that came with the snapshot. sink, err := r.snapshots.Create(version, lastIndex, term, r.configurations.latest, r.configurations.latestIndex, r.trans) if err != nil { return fmt.Errorf("failed to create snapshot: %v", err) } n, err := io.Copy(sink, reader) if err != nil { sink.Cancel() return fmt.Errorf("failed to write snapshot: %v", err) } if n != meta.Size { sink.Cancel() return fmt.Errorf("failed to write snapshot, size didn't match (%d != %d)", n, meta.Size) } if err := sink.Close(); err != nil { return fmt.Errorf("failed to close snapshot: %v", err) } r.logger.Info(fmt.Sprintf("Copied %d bytes to local snapshot", n)) // Restore the snapshot into the FSM. If this fails we are in a // bad state so we panic to take ourselves out. fsm := &restoreFuture{ID: sink.ID()} fsm.init() select { case r.fsmMutateCh <- fsm: case <-r.shutdownCh: return ErrRaftShutdown } if err := fsm.Error(); err != nil { panic(fmt.Errorf("failed to restore snapshot: %v", err)) } // We set the last log so it looks like we've stored the empty // index we burned. The last applied is set because we made the // FSM take the snapshot state, and we store the last snapshot // in the stable store since we created a snapshot as part of // this process. r.setLastLog(lastIndex, term) r.setLastApplied(lastIndex) r.setLastSnapshot(lastIndex, term) r.logger.Info(fmt.Sprintf("Restored user snapshot (index %d)", lastIndex)) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L39-L41
func (p *DeliverPushMessageParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandDeliverPushMessage, p, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/main.go#L105-L125
func newPipelineConfig(cfg rest.Config, stop chan struct{}) (*pipelineConfig, error) { bc, err := pipelineset.NewForConfig(&cfg) if err != nil { return nil, err } // Ensure the pipeline CRD is deployed // TODO(fejta): probably a better way to do this if _, err := bc.TektonV1alpha1().PipelineRuns("").List(metav1.ListOptions{Limit: 1}); err != nil { return nil, err } // Assume watches receive updates, but resync every 30m in case something wonky happens bif := pipelineinfo.NewSharedInformerFactory(bc, 30*time.Minute) bif.Tekton().V1alpha1().PipelineRuns().Lister() go bif.Start(stop) return &pipelineConfig{ client: bc, informer: bif.Tekton().V1alpha1().PipelineRuns(), }, nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/paths.go#L179-L181
func umGroupSharePath(grpid string, resourceid string) string { return um() + slash("groups") + slash(grpid) + slash("shares") + slash(resourceid) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5965-L5968
func (e ErrorCode) String() string { name, _ := errorCodeMap[int32(e)] return name }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approve.go#L201-L210
func handleReviewEvent(pc plugins.Agent, re github.ReviewEvent) error { return handleReview( pc.Logger, pc.GitHubClient, pc.OwnersClient, pc.Config.GitHubOptions, pc.PluginConfig, &re, ) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/workload/workload.go#L121-L151
func (w *worker) advanceCommit(c *client.APIClient) error { if len(w.started) >= maxStartedCommits || len(w.finished) == 0 { // Randomly select a commit that has been started and finish it if len(w.started) == 0 { return nil } i := w.rand.Intn(len(w.started)) commit := w.started[i] // Before we finish a commit, we add a file. This assures that there // won't be any empty commits which will later crash jobs if _, err := c.PutFile(commit.Repo.Name, commit.ID, w.randString(10), w.reader()); err != nil { return err } if err := c.FinishCommit(commit.Repo.Name, commit.ID); err != nil { return err } // remove commit[i] from 'started' and add it to 'finished' w.started = append(w.started[:i], w.started[i+1:]...) w.finished = append(w.finished, commit) } else { // Start a new commmit (parented off of a commit that we've finished) commit := w.finished[w.rand.Intn(len(w.finished))] commit, err := c.StartCommitParent(commit.Repo.Name, "", commit.ID) if err != nil { return err } w.started = append(w.started, commit) } return nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L609-L612
func (writer *VideoWriter) Release() { writer_c := (*C.CvVideoWriter)(writer) C.cvReleaseVideoWriter(&writer_c) }
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/stream.go#L27-L37
func newStream(bufsize int, replay bool) *Stream { return &Stream{ AutoReplay: replay, subscribers: make([]*Subscriber, 0), register: make(chan *Subscriber), deregister: make(chan *Subscriber), event: make(chan *Event, bufsize), quit: make(chan bool), Eventlog: make(EventLog, 0), } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L236-L251
func (in *ProwJobStatus) DeepCopyInto(out *ProwJobStatus) { *out = *in in.StartTime.DeepCopyInto(&out.StartTime) if in.CompletionTime != nil { in, out := &in.CompletionTime, &out.CompletionTime *out = (*in).DeepCopy() } if in.PrevReportStates != nil { in, out := &in.PrevReportStates, &out.PrevReportStates *out = make(map[string]ProwJobState, len(*in)) for key, val := range *in { (*out)[key] = val } } return }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/streambuffer/streambuffer.go#L54-L58
func (s *Stream) SetLogger(log ttnlog.Interface) { s.mu.Lock() s.log = log s.mu.Unlock() }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L395-L402
func FileSequence_InvertedFrameRange(id FileSeqId) *C.char { fs, ok := sFileSeqs.Get(id) // caller must free string if !ok { return C.CString("") } return C.CString(fs.InvertedFrameRange()) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/sourced.go#L67-L89
func FromUnparsedImage(ctx context.Context, sys *types.SystemContext, unparsed *UnparsedImage) (types.Image, error) { // Note that the input parameter above is specifically *image.UnparsedImage, not types.UnparsedImage: // we want to be able to use unparsed.src. We could make that an explicit interface, but, well, // this is the only UnparsedImage implementation around, anyway. // NOTE: It is essential for signature verification that all parsing done in this object happens on the same manifest which is returned by unparsed.Manifest(). manifestBlob, manifestMIMEType, err := unparsed.Manifest(ctx) if err != nil { return nil, err } parsedManifest, err := manifestInstanceFromBlob(ctx, sys, unparsed.src, manifestBlob, manifestMIMEType) if err != nil { return nil, err } return &sourcedImage{ UnparsedImage: unparsed, manifestBlob: manifestBlob, manifestMIMEType: manifestMIMEType, genericManifest: parsedManifest, }, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/client.go#L129-L154
func parseConfig(config *Configuration) error { if config.InitialNodesFile != "" { f, err := os.Open(config.InitialNodesFile) if err != nil { return err } defer f.Close() decoder := json.NewDecoder(f) if err := decoder.Decode(&config.InitialNodes); err != nil { return err } } if len(config.InitialNodes) == 0 { return fmt.Errorf("hyperbahn Client requires at least one initial node") } for _, node := range config.InitialNodes { if _, _, err := net.SplitHostPort(node); err != nil { return fmt.Errorf("hyperbahn Client got invalid node %v: %v", node, err) } } return nil }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/recovery/recovery.go#L38-L43
func WithPanicResponse(body, contentType string) Option { return func(o *Handler) { o.panicBody = body o.panicContentType = contentType } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L689-L697
func (ch *Channel) removeClosedConn(c *Connection) { if c.readState() != connectionClosed { return } ch.mutable.Lock() delete(ch.mutable.conns, c.connID) ch.mutable.Unlock() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/types.go#L38-L40
func (t SetTimeDomainTimeDomain) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/api_server.go#L1970-L2023
func setPipelineDefaults(pipelineInfo *pps.PipelineInfo) { now := time.Now() if pipelineInfo.Transform.Image == "" { pipelineInfo.Transform.Image = DefaultUserImage } pps.VisitInput(pipelineInfo.Input, func(input *pps.Input) { if input.Pfs != nil { if input.Pfs.Branch == "" { input.Pfs.Branch = "master" } if input.Pfs.Name == "" { input.Pfs.Name = input.Pfs.Repo } } if input.Cron != nil { if input.Cron.Start == nil { start, _ := types.TimestampProto(now) input.Cron.Start = start } if input.Cron.Repo == "" { input.Cron.Repo = fmt.Sprintf("%s_%s", pipelineInfo.Pipeline.Name, input.Cron.Name) } } if input.Git != nil { if input.Git.Branch == "" { input.Git.Branch = "master" } if input.Git.Name == "" { // We know URL looks like: // "https://github.com/sjezewski/testgithook.git", tokens := strings.Split(path.Base(input.Git.URL), ".") input.Git.Name = tokens[0] } } }) if pipelineInfo.OutputBranch == "" { // Output branches default to master pipelineInfo.OutputBranch = "master" } if pipelineInfo.CacheSize == "" { pipelineInfo.CacheSize = "64M" } if pipelineInfo.ResourceRequests == nil && pipelineInfo.CacheSize != "" { pipelineInfo.ResourceRequests = &pps.ResourceSpec{ Memory: pipelineInfo.CacheSize, } } if pipelineInfo.MaxQueueSize < 1 { pipelineInfo.MaxQueueSize = 1 } if pipelineInfo.DatumTries == 0 { pipelineInfo.DatumTries = DefaultDatumTries } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L728-L735
func AAParseProfile(c container) error { state := c.DaemonState() if !state.OS.AppArmorAvailable { return nil } return runApparmor(APPARMOR_CMD_PARSE, c) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5753-L5757
func (v *FontFace) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss50(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L664-L667
func (c *Cluster) ImageAliasesMove(source int, destination int) error { err := exec(c.db, "UPDATE images_aliases SET image_id=? WHERE image_id=?", destination, source) return err }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L382-L384
func (b *Base) Debug(msg string) error { return b.Log(LevelDebug, nil, msg) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/githuboauth/githuboauth.go#L84-L89
func NewAgent(config *config.GitHubOAuthConfig, logger *logrus.Entry) *Agent { return &Agent{ gc: config, logger: logger, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/build/controller.go#L574-L576
func buildEnv(pj prowjobv1.ProwJob, buildID string) (map[string]string, error) { return downwardapi.EnvForSpec(downwardapi.NewJobSpec(pj.Spec, buildID, pj.Name)) }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/encode.go#L30-L35
func NewEncoder(e Emitter) *Encoder { if e == nil { panic("objconv: the emitter is nil") } return &Encoder{Emitter: e} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdproto.go#L70-L72
func (t MethodType) Domain() string { return string(t[:strings.IndexByte(string(t), '.')]) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/config.go#L32-L41
func FindRuleWithOverride(c *config.Config, imp ImportSpec, lang string) (label.Label, bool) { rc := getResolveConfig(c) for i := len(rc.overrides) - 1; i >= 0; i-- { o := rc.overrides[i] if o.matches(imp, lang) { return o.dep, true } } return label.NoLabel, false }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L553-L557
func (r *Raft) handleStaleTerm(s *followerReplication) { r.logger.Error(fmt.Sprintf("peer %v has newer term, stopping replication", s.peer)) s.notifyAll(false) // No longer leader asyncNotifyCh(s.stepDown) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L126-L132
func (c *Cluster) CertUpdate(fingerprint string, certName string, certType int) error { err := c.Transaction(func(tx *ClusterTx) error { _, err := tx.tx.Exec("UPDATE certificates SET name=?, type=? WHERE fingerprint=?", certName, certType, fingerprint) return err }) return err }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/decoder.go#L63-L66
func NewDecoderSize(reg Registry, maxSize uint64, r io.Reader) Decoder { var buf []byte return decoder{reg, maxSize, bytes.NewBuffer(buf), bufio.NewReader(r)} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L153-L157
func (v *SetInstrumentationBreakpointParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomdebugger1(&r, v) return r.Error() }