_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L98-L115
|
func (s *Storage) Start(ctx context.Context, accessToken, refreshToken, sid, sc string, b map[string]string) (*mnemosynerpc.Session, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "postgres.storage.start")
defer span.Finish()
ent := &sessionEntity{
AccessToken: accessToken,
RefreshToken: refreshToken,
SubjectID: sid,
SubjectClient: sc,
Bag: model.Bag(b),
}
if err := s.save(ctx, ent); err != nil {
return nil, err
}
return ent.session()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L107-L142
|
func (b *backup) Rename(newName string) error {
oldBackupPath := shared.VarPath("backups", b.name)
newBackupPath := shared.VarPath("backups", newName)
// Create the new backup path
backupsPath := shared.VarPath("backups", b.container.Name())
if !shared.PathExists(backupsPath) {
err := os.MkdirAll(backupsPath, 0700)
if err != nil {
return err
}
}
// Rename the backup directory
err := os.Rename(oldBackupPath, newBackupPath)
if err != nil {
return err
}
// Check if we can remove the container directory
empty, _ := shared.PathIsEmpty(backupsPath)
if empty {
err := os.Remove(backupsPath)
if err != nil {
return err
}
}
// Rename the database record
err = b.state.Cluster.ContainerBackupRename(b.name, newName)
if err != nil {
return err
}
return nil
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/process.go#L533-L555
|
func (p *Process) splitMappingsAt(a Address) {
for _, m := range p.memory.mappings {
if a < m.min || a > m.max {
continue
}
if a == m.min || a == m.max {
return
}
// Split this mapping at a.
m2 := new(Mapping)
*m2 = *m
m.max = a
m2.min = a
if m2.f != nil {
m2.off += m.Size()
}
if m2.origF != nil {
m2.origOff += m.Size()
}
p.memory.mappings = append(p.memory.mappings, m2)
return
}
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/ipblock.go#L56-L61
|
func (c *Client) GetIPBlock(ipblockid string) (*IPBlock, error) {
url := ipblockPath(ipblockid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &IPBlock{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L345-L382
|
func (a *API) parseResource(cmd, hrefPrefix string, commandValues ActionCommands) (*metadata.Resource, []*metadata.PathVariable, error) {
elems := strings.Split(cmd, " ")
actionName := elems[len(elems)-1]
flags := commandValues[cmd]
if flags == nil {
return nil, nil, fmt.Errorf("Invalid command line, try --help.")
}
href := flags.Href
if hrefPrefix != "" && !strings.HasPrefix(href, hrefPrefix) {
href = path.Join(hrefPrefix, href)
}
var vars []*metadata.PathVariable
var candidates []*metadata.Resource
Metadata:
for _, res := range a.Metadata {
if v, err := res.ExtractVariables(href); err == nil {
vars = v
for _, a := range res.Actions {
if a.Name == actionName && a.MatchHref(href) {
// We found an exact match!
candidates = []*metadata.Resource{res}
break Metadata
}
}
candidates = append(candidates, res)
}
}
if len(candidates) == 0 {
return nil, nil, fmt.Errorf("Invalid href '%s'. Try '%s %s actions'.", href,
os.Args[0], strings.Split(cmd, " ")[0])
}
if len(candidates) > 1 {
return nil, nil, fmt.Errorf("Invalid href '%s'. Multiple resources have an action '%s' that match this href. Try '%s %s actions' and specify a more complete href.",
href, actionName, os.Args[0], strings.Split(cmd, " ")[0])
}
return candidates[0], vars, nil
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/router.go#L159-L181
|
func (rt *router) findRouteFromURL(httpMethod string, urlObj *url.URL) (*Route, map[string]string, bool) {
// lookup the routes in the Trie
matches, pathMatched := rt.trie.FindRoutesAndPathMatched(
strings.ToUpper(httpMethod), // work with the httpMethod in uppercase
escapedPath(urlObj), // work with the path urlencoded
)
// short cuts
if len(matches) == 0 {
// no route found
return nil, nil, pathMatched
}
if len(matches) == 1 {
// one route found
return matches[0].Route.(*Route), matches[0].Params, pathMatched
}
// multiple routes found, pick the first defined
result := rt.ofFirstDefinedRoute(matches)
return result.Route.(*Route), result.Params, pathMatched
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/builder.go#L159-L171
|
func (b *Builder) Add(key []byte, value y.ValueStruct) error {
if b.counter >= restartInterval {
b.finishBlock()
// Start a new block. Initialize the block.
b.restarts = append(b.restarts, uint32(b.buf.Len()))
b.counter = 0
b.baseKey = []byte{}
b.baseOffset = uint32(b.buf.Len())
b.prevOffset = math.MaxUint32 // First key-value pair of block has header.prev=MaxInt.
}
b.addHelper(key, value)
return nil // Currently, there is no meaningful error.
}
|
https://github.com/imdario/mergo/blob/45df20b7fcedb0ff48e461334a1f0aafcc3892e3/map.go#L34-L119
|
func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) {
overwrite := config.Overwrite
if dst.CanAddr() {
addr := dst.UnsafeAddr()
h := 17 * addr
seen := visited[h]
typ := dst.Type()
for p := seen; p != nil; p = p.next {
if p.ptr == addr && p.typ == typ {
return nil
}
}
// Remember, remember...
visited[h] = &visit{addr, typ, seen}
}
zeroValue := reflect.Value{}
switch dst.Kind() {
case reflect.Map:
dstMap := dst.Interface().(map[string]interface{})
for i, n := 0, src.NumField(); i < n; i++ {
srcType := src.Type()
field := srcType.Field(i)
if !isExported(field) {
continue
}
fieldName := field.Name
fieldName = changeInitialCase(fieldName, unicode.ToLower)
if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v)) || overwrite) {
dstMap[fieldName] = src.Field(i).Interface()
}
}
case reflect.Ptr:
if dst.IsNil() {
v := reflect.New(dst.Type().Elem())
dst.Set(v)
}
dst = dst.Elem()
fallthrough
case reflect.Struct:
srcMap := src.Interface().(map[string]interface{})
for key := range srcMap {
config.overwriteWithEmptyValue = true
srcValue := srcMap[key]
fieldName := changeInitialCase(key, unicode.ToUpper)
dstElement := dst.FieldByName(fieldName)
if dstElement == zeroValue {
// We discard it because the field doesn't exist.
continue
}
srcElement := reflect.ValueOf(srcValue)
dstKind := dstElement.Kind()
srcKind := srcElement.Kind()
if srcKind == reflect.Ptr && dstKind != reflect.Ptr {
srcElement = srcElement.Elem()
srcKind = reflect.TypeOf(srcElement.Interface()).Kind()
} else if dstKind == reflect.Ptr {
// Can this work? I guess it can't.
if srcKind != reflect.Ptr && srcElement.CanAddr() {
srcPtr := srcElement.Addr()
srcElement = reflect.ValueOf(srcPtr)
srcKind = reflect.Ptr
}
}
if !srcElement.IsValid() {
continue
}
if srcKind == dstKind {
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface {
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else if srcKind == reflect.Map {
if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else {
return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind)
}
}
}
return
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/observer.go#L60-L67
|
func NewObserver(channel chan Observation, blocking bool, filter FilterFn) *Observer {
return &Observer{
channel: channel,
blocking: blocking,
filter: filter,
id: atomic.AddUint64(&nextObserverID, 1),
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L677-L685
|
func (r *ProtocolLXD) UpdateImageAlias(name string, alias api.ImageAliasesEntryPut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, ETag)
if err != nil {
return err
}
return nil
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/mailing_list.go#L63-L75
|
func (dom *Domain) MailingLists() ([]*MailingList, error) {
var vl valueList
err := dom.cgp.request(listLists{Domain: dom.Name}, &vl)
if err != nil {
return []*MailingList{}, err
}
vals := vl.compact()
mls := make([]*MailingList, len(vals))
for i, v := range vals {
mls[i] = dom.MailingList(v)
}
return mls, nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L668-L670
|
func AddScalar(src *IplImage, value Scalar, dst *IplImage) {
AddScalarWithMask(src, value, dst, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L184-L224
|
func (m *Map) set(name string, value string, initial bool) (bool, error) {
key, ok := m.schema[name]
if !ok {
return false, fmt.Errorf("unknown key")
}
err := key.validate(value)
if err != nil {
return false, err
}
// Normalize boolan values, so the comparison below works fine.
current := m.GetRaw(name)
if key.Type == Bool {
value = normalizeBool(value)
current = normalizeBool(current)
}
// Compare the new value with the current one, and return now if they
// are equal.
if value == current {
return false, nil
}
// Trigger the Setter if this is not an initial load and the key's
// schema has declared it.
if !initial && key.Setter != nil {
value, err = key.Setter(value)
if err != nil {
return false, err
}
}
if value == "" {
delete(m.values, name)
} else {
m.values[name] = value
}
return true, nil
}
|
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dominator.go#L199-L266
|
func (d *ltDom) calculate() {
// name -> bucket (a name), per Georgiadis.
buckets := make([]vName, d.nVertices)
for i := range buckets {
buckets[i] = vName(i)
}
for i := vNumber(len(d.vertices)) - 1; i > 0; i-- {
w := d.vertices[i]
// Step 3. Implicitly define the immediate dominator of each node.
for v := buckets[w]; v != w; v = buckets[v] {
u := d.eval(v)
if d.semis[u] < d.semis[v] {
d.idom[v] = u
} else {
d.idom[v] = w
}
}
// Step 2. Compute the semidominators of all nodes.
root, obj := d.findVertexByName(w)
// This loop never visits the pseudo-root.
if root != nil {
u := d.eval(pseudoRoot)
if d.semis[u] < d.semis[w] {
d.semis[w] = d.semis[u]
}
} else {
d.p.ForEachReversePtr(obj, func(x Object, r *Root, _, _ int64) bool {
var v int
if r != nil {
v = d.p.findRootIndex(r) + 1
} else {
v, _ = d.p.findObjectIndex(d.p.Addr(x))
v += d.nRoots + 1
}
u := d.eval(vName(v))
if d.semis[u] < d.semis[w] {
d.semis[w] = d.semis[u]
}
return true
})
}
d.link(d.parents[w], w)
if d.parents[w] == d.vertices[d.semis[w]] {
d.idom[w] = d.parents[w]
} else {
buckets[w] = buckets[d.vertices[d.semis[w]]]
buckets[d.vertices[d.semis[w]]] = w
}
}
// The final 'Step 3' is now outside the loop.
for v := buckets[pseudoRoot]; v != pseudoRoot; v = buckets[v] {
d.idom[v] = pseudoRoot
}
// Step 4. Explicitly define the immediate dominator of each
// node, in preorder.
for _, w := range d.vertices[1:] {
if d.idom[w] != d.vertices[d.semis[w]] {
d.idom[w] = d.idom[d.idom[w]]
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L781-L784
|
func (p SetCookieParams) WithSecure(secure bool) *SetCookieParams {
p.Secure = secure
return &p
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L210-L223
|
func (api *TelegramBotAPI) NewOutgoingDocument(recipient Recipient, fileName string, reader io.Reader) *OutgoingDocument {
return &OutgoingDocument{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileName: fileName,
r: reader,
},
}
}
|
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_github.go#L67-L144
|
func (h *Github) Fetch() (io.Reader, error) {
//delay fetches after first
if h.delay {
time.Sleep(h.Interval)
}
h.delay = true
//check release status
resp, err := http.Get(h.releaseURL)
if err != nil {
return nil, fmt.Errorf("release info request failed (%s)", err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("release info request failed (status code %d)", resp.StatusCode)
}
//clear assets
h.latestRelease.Assets = nil
if err := json.NewDecoder(resp.Body).Decode(&h.latestRelease); err != nil {
return nil, fmt.Errorf("invalid request info (%s)", err)
}
resp.Body.Close()
//find appropriate asset
assetURL := ""
for _, a := range h.latestRelease.Assets {
if h.Asset(a.Name) {
assetURL = a.URL
break
}
}
if assetURL == "" {
return nil, fmt.Errorf("no matching assets in this release (%s)", h.latestRelease.TagName)
}
//fetch location
req, _ := http.NewRequest("HEAD", assetURL, nil)
resp, err = http.DefaultTransport.RoundTrip(req)
if err != nil {
return nil, fmt.Errorf("release location request failed (%s)", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusFound {
return nil, fmt.Errorf("release location request failed (status code %d)", resp.StatusCode)
}
s3URL := resp.Header.Get("Location")
//pseudo-HEAD request
req, err = http.NewRequest("GET", s3URL, nil)
if err != nil {
return nil, fmt.Errorf("release location url error (%s)", err)
}
req.Header.Set("Range", "bytes=0-0") // HEAD not allowed so we request for 1 byte
resp, err = http.DefaultTransport.RoundTrip(req)
if err != nil {
return nil, fmt.Errorf("release location request failed (%s)", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusPartialContent {
return nil, fmt.Errorf("release location request failed (status code %d)", resp.StatusCode)
}
etag := resp.Header.Get("ETag")
if etag != "" && h.lastETag == etag {
return nil, nil //skip, hash match
}
//get binary request
resp, err = http.Get(s3URL)
if err != nil {
return nil, fmt.Errorf("release binary request failed (%s)", err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("release binary request failed (status code %d)", resp.StatusCode)
}
h.lastETag = etag
//success!
//extract gz files
if strings.HasSuffix(assetURL, ".gz") && resp.Header.Get("Content-Encoding") != "gzip" {
return gzip.NewReader(resp.Body)
}
return resp.Body, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1156-L1159
|
func (p StartScreencastParams) WithMaxHeight(maxHeight int64) *StartScreencastParams {
p.MaxHeight = maxHeight
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1875-L1879
|
func (v *SearchMatch) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger19(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L270-L272
|
func (t *PausedReason) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L674-L676
|
func (o *RepoOwners) RequiredReviewers(path string) sets.String {
return o.entriesForFile(path, o.requiredReviewers, false)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L116-L125
|
func buildContext(tags []string) *build.Context {
return &build.Context{
GOARCH: build.Default.GOARCH,
GOOS: build.Default.GOOS,
GOROOT: build.Default.GOROOT,
GOPATH: build.Default.GOPATH,
Compiler: build.Default.Compiler,
BuildTags: append(build.Default.BuildTags, tags...),
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/read_only.go#L78-L109
|
func (ro *readOnly) advance(m pb.Message) []*readIndexStatus {
var (
i int
found bool
)
ctx := string(m.Context)
rss := []*readIndexStatus{}
for _, okctx := range ro.readIndexQueue {
i++
rs, ok := ro.pendingReadIndex[okctx]
if !ok {
panic("cannot find corresponding read state from pending map")
}
rss = append(rss, rs)
if okctx == ctx {
found = true
break
}
}
if found {
ro.readIndexQueue = ro.readIndexQueue[i:]
for _, rs := range rss {
delete(ro.pendingReadIndex, string(rs.req.Entries[0].Data))
}
return rss
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L159-L171
|
func (o Owners) GetSuggestedApprovers(reverseMap map[string]sets.String, potentialApprovers []string) sets.String {
ap := NewApprovers(o)
for !ap.RequirementsMet() {
newApprover := findMostCoveringApprover(potentialApprovers, reverseMap, ap.UnapprovedFiles())
if newApprover == "" {
o.log.Warnf("Couldn't find/suggest approvers for each files. Unapproved: %q", ap.UnapprovedFiles().List())
return ap.GetCurrentApproversSet()
}
ap.AddApprover(newApprover, "", false)
}
return ap.GetCurrentApproversSet()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L668-L671
|
func (p SetBreakpointByURLParams) WithURL(url string) *SetBreakpointByURLParams {
p.URL = url
return &p
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/tools.go#L47-L89
|
func EnsureApplication(store *coal.Store, name, key, secret string) (string, error) {
// copy store
s := store.Copy()
defer s.Close()
// count main applications
var apps []Application
err := s.C(&Application{}).Find(bson.M{
coal.F(&Application{}, "Name"): name,
}).All(&apps)
if err != nil {
return "", err
}
// check existence
if len(apps) > 1 {
return "", errors.New("to many applications with that name")
} else if len(apps) == 1 {
return apps[0].Key, nil
}
// application is missing
// create application
app := coal.Init(&Application{}).(*Application)
app.Key = key
app.Name = name
app.Secret = secret
// validate model
err = app.Validate()
if err != nil {
return "", err
}
// save application
err = s.C(app).Insert(app)
if err != nil {
return "", err
}
return app.Key, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L38-L43
|
func NewCommitProvenance(repoName string, branchName string, commitID string) *pfs.CommitProvenance {
return &pfs.CommitProvenance{
Commit: NewCommit(repoName, commitID),
Branch: NewBranch(repoName, branchName),
}
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/encode.go#L38-L230
|
func (e Encoder) Encode(v interface{}) (err error) {
if err = e.encodeMapValueMaybe(); err != nil {
return
}
// This type switch optimizes encoding of common value types, it prevents
// the use of reflection to identify the type of the value, which saves a
// dynamic memory allocation.
switch x := v.(type) {
case nil:
return e.Emitter.EmitNil()
case bool:
return e.Emitter.EmitBool(x)
case int:
return e.Emitter.EmitInt(int64(x), 0)
case int8:
return e.Emitter.EmitInt(int64(x), 8)
case int16:
return e.Emitter.EmitInt(int64(x), 16)
case int32:
return e.Emitter.EmitInt(int64(x), 32)
case int64:
return e.Emitter.EmitInt(x, 64)
case uint8:
return e.Emitter.EmitUint(uint64(x), 8)
case uint16:
return e.Emitter.EmitUint(uint64(x), 16)
case uint32:
return e.Emitter.EmitUint(uint64(x), 32)
case uint64:
return e.Emitter.EmitUint(x, 64)
case string:
return e.Emitter.EmitString(x)
case []byte:
return e.Emitter.EmitBytes(x)
case time.Time:
return e.Emitter.EmitTime(x)
case time.Duration:
return e.Emitter.EmitDuration(x)
case []string:
return e.encodeSliceOfString(x)
case []interface{}:
return e.encodeSliceOfInterface(x)
case map[string]string:
return e.encodeMapStringString(x)
case map[string]interface{}:
return e.encodeMapStringInterface(x)
case map[interface{}]interface{}:
return e.encodeMapInterfaceInterface(x)
// Also checks for pointer types so the program can use this as a way
// to avoid the dynamic memory allocation done by runtime.convT2E for
// converting non-pointer types to empty interfaces.
case *bool:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitBool(*x)
case *int:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitInt(int64(*x), int(8*unsafe.Sizeof(0)))
case *int8:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitInt(int64(*x), 8)
case *int16:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitInt(int64(*x), 16)
case *int32:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitInt(int64(*x), 32)
case *int64:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitInt(*x, 64)
case *uint8:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitUint(uint64(*x), 8)
case *uint16:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitUint(uint64(*x), 16)
case *uint32:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitUint(uint64(*x), 32)
case *uint64:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitUint(*x, 64)
case *string:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitString(*x)
case *[]byte:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitBytes(*x)
case *time.Time:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitTime(*x)
case *time.Duration:
if x == nil {
return e.Emitter.EmitNil()
}
return e.Emitter.EmitDuration(*x)
case *[]string:
if x == nil {
return e.Emitter.EmitNil()
}
return e.encodeSliceOfString(*x)
case *[]interface{}:
if x == nil {
return e.Emitter.EmitNil()
}
return e.encodeSliceOfInterface(*x)
case *map[string]string:
if x == nil {
return e.Emitter.EmitNil()
}
return e.encodeMapStringString(*x)
case *map[string]interface{}:
if x == nil {
return e.Emitter.EmitNil()
}
return e.encodeMapStringInterface(*x)
case *map[interface{}]interface{}:
if x == nil {
return e.Emitter.EmitNil()
}
return e.encodeMapInterfaceInterface(*x)
case ValueEncoder:
return x.EncodeValue(e)
default:
return e.encode(reflect.ValueOf(v))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L47-L50
|
func (p DispatchKeyEventParams) WithModifiers(modifiers Modifier) *DispatchKeyEventParams {
p.Modifiers = modifiers
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1723-L1727
|
func (v *CloseParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser19(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/writer.go#L64-L77
|
func (w *LogWriter) Write(data []byte) (int, error) {
w.finLk.RLock()
defer w.finLk.RUnlock()
if w.closed {
return len(data), nil
}
if w.msgCh == nil {
return len(data), w.write(data)
}
copied := make([]byte, len(data))
copy(copied, data)
w.msgCh <- copied
return len(data), nil
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1282-L1287
|
func NewStreamDecoder(p Parser) *StreamDecoder {
if p == nil {
panic("objconv: the parser is nil")
}
return &StreamDecoder{Parser: p}
}
|
https://github.com/giantswarm/certctl/blob/2a6615f61499cd09a8d5ced9a5fade322d2de254/service/cert-signer/cert_signer.go#L41-L52
|
func New(config Config) (spec.CertSigner, error) {
newCertSigner := &certSigner{
Config: config,
}
// Dependencies.
if newCertSigner.VaultClient == nil {
return nil, microerror.Maskf(invalidConfigError, "Vault client must not be empty")
}
return newCertSigner, nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L183-L205
|
func buildUpdateRelMap(root string, dirs []string) map[string]bool {
relMap := make(map[string]bool)
for _, dir := range dirs {
rel, _ := filepath.Rel(root, dir)
rel = filepath.ToSlash(rel)
if rel == "." {
rel = ""
}
i := 0
for {
next := strings.IndexByte(rel[i:], '/') + i
if next-i < 0 {
relMap[rel] = true
break
}
prefix := rel[:next]
relMap[prefix] = relMap[prefix] // set to false if not present
i = next + 1
}
}
return relMap
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L8458-L8462
|
func (v CachedResource) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork66(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L98-L129
|
func (m *Message) Send(c context.Context) error {
req := &pb.XmppMessageRequest{
Jid: m.To,
Body: &m.Body,
RawXml: &m.RawXML,
}
if m.Type != "" && m.Type != "chat" {
req.Type = &m.Type
}
if m.Sender != "" {
req.FromJid = &m.Sender
}
res := &pb.XmppMessageResponse{}
if err := internal.Call(c, "xmpp", "SendMessage", req, res); err != nil {
return err
}
if len(res.Status) != len(req.Jid) {
return fmt.Errorf("xmpp: sent message to %d JIDs, but only got %d statuses back", len(req.Jid), len(res.Status))
}
me, any := make(appengine.MultiError, len(req.Jid)), false
for i, st := range res.Status {
if st != pb.XmppMessageResponse_NO_ERROR {
me[i] = errors.New(st.String())
any = true
}
}
if any {
return me
}
return nil
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L124-L187
|
func NewReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (*Reader, error) {
buf := make([]byte, 10)
f.ReadAt(buf, 0)
if !bytes.HasPrefix(buf, []byte("%PDF-1.")) || buf[7] < '0' || buf[7] > '7' || buf[8] != '\r' && buf[8] != '\n' {
return nil, fmt.Errorf("not a PDF file: invalid header")
}
end := size
const endChunk = 100
buf = make([]byte, endChunk)
f.ReadAt(buf, end-endChunk)
for len(buf) > 0 && buf[len(buf)-1] == '\n' || buf[len(buf)-1] == '\r' {
buf = buf[:len(buf)-1]
}
buf = bytes.TrimRight(buf, "\r\n\t ")
if !bytes.HasSuffix(buf, []byte("%%EOF")) {
return nil, fmt.Errorf("not a PDF file: missing %%%%EOF")
}
i := findLastLine(buf, "startxref")
if i < 0 {
return nil, fmt.Errorf("malformed PDF file: missing final startxref")
}
r := &Reader{
f: f,
end: end,
}
pos := end - endChunk + int64(i)
b := newBuffer(io.NewSectionReader(f, pos, end-pos), pos)
if b.readToken() != keyword("startxref") {
return nil, fmt.Errorf("malformed PDF file: missing startxref")
}
startxref, ok := b.readToken().(int64)
if !ok {
return nil, fmt.Errorf("malformed PDF file: startxref not followed by integer")
}
b = newBuffer(io.NewSectionReader(r.f, startxref, r.end-startxref), startxref)
xref, trailerptr, trailer, err := readXref(r, b)
if err != nil {
return nil, err
}
r.xref = xref
r.trailer = trailer
r.trailerptr = trailerptr
if trailer["Encrypt"] == nil {
return r, nil
}
err = r.initEncrypt("")
if err == nil {
return r, nil
}
if pw == nil || err != ErrInvalidPassword {
return nil, err
}
for {
next := pw()
if next == "" {
break
}
if r.initEncrypt(next) == nil {
return r, nil
}
}
return nil, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L56-L70
|
func (c *ClusterTx) StoragePoolDriver(id int64) (string, error) {
stmt := "SELECT driver FROM storage_pools WHERE id=?"
drivers, err := query.SelectStrings(c.tx, stmt, id)
if err != nil {
return "", err
}
switch len(drivers) {
case 0:
return "", ErrNoSuchObject
case 1:
return drivers[0], nil
default:
return "", fmt.Errorf("more than one pool has the given id")
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5781-L5790
|
func (u LedgerEntryChange) GetUpdated() (result LedgerEntry, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Updated" {
result = *u.Updated
ok = true
}
return
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/config.go#L141-L162
|
func LoadClusterConfigs(kubeconfig, buildCluster string) (map[string]rest.Config, error) {
logrus.Infof("Loading cluster contexts...")
// This will work if we are running inside kubernetes
localCfg, err := localConfig()
if err != nil {
logrus.WithError(err).Warn("Could not create in-cluster config (expected when running outside the cluster).")
}
kubeCfgs, currentContext, err := kubeConfigs(kubeconfig)
if err != nil {
return nil, fmt.Errorf("kubecfg: %v", err)
}
// TODO(fejta): drop build-cluster support
buildCfgs, err := buildConfigs(buildCluster)
if err != nil {
return nil, fmt.Errorf("build-cluster: %v", err)
}
return mergeConfigs(localCfg, kubeCfgs, currentContext, buildCfgs)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L1044-L1097
|
func (d *driver) resolveCommit(stm col.STM, userCommit *pfs.Commit) (*pfs.CommitInfo, error) {
if userCommit == nil {
return nil, fmt.Errorf("cannot resolve nil commit")
}
if userCommit.ID == "" {
return nil, fmt.Errorf("cannot resolve commit with no ID or branch")
}
commit := proto.Clone(userCommit).(*pfs.Commit) // back up user commit, for error reporting
// Extract any ancestor tokens from 'commit.ID' (i.e. ~ and ^)
var ancestryLength int
commit.ID, ancestryLength = ancestry.Parse(commit.ID)
// Keep track of the commit branch, in case it isn't set in the commitInfo already
var commitBranch *pfs.Branch
// Check if commit.ID is already a commit ID (i.e. a UUID).
if !uuid.IsUUIDWithoutDashes(commit.ID) {
branches := d.branches(commit.Repo.Name).ReadWrite(stm)
branchInfo := &pfs.BranchInfo{}
// See if we are given a branch
if err := branches.Get(commit.ID, branchInfo); err != nil {
return nil, err
}
if branchInfo.Head == nil {
return nil, pfsserver.ErrNoHead{branchInfo.Branch}
}
commitBranch = branchInfo.Branch
commit.ID = branchInfo.Head.ID
}
// Traverse commits' parents until you've reached the right ancestor
commits := d.commits(commit.Repo.Name).ReadWrite(stm)
commitInfo := &pfs.CommitInfo{}
for i := 0; i <= ancestryLength; i++ {
if commit == nil {
return nil, pfsserver.ErrCommitNotFound{userCommit}
}
childCommit := commit // preserve child for error reporting
if err := commits.Get(commit.ID, commitInfo); err != nil {
if col.IsErrNotFound(err) {
if i == 0 {
return nil, pfsserver.ErrCommitNotFound{childCommit}
}
return nil, pfsserver.ErrParentCommitNotFound{childCommit}
}
return nil, err
}
commit = commitInfo.ParentCommit
}
if commitInfo.Branch == nil {
commitInfo.Branch = commitBranch
}
userCommit.ID = commitInfo.Commit.ID
return commitInfo, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/types.go#L77-L109
|
func (t *Source) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch Source(in.String()) {
case SourceXML:
*t = SourceXML
case SourceJavascript:
*t = SourceJavascript
case SourceNetwork:
*t = SourceNetwork
case SourceStorage:
*t = SourceStorage
case SourceAppcache:
*t = SourceAppcache
case SourceRendering:
*t = SourceRendering
case SourceSecurity:
*t = SourceSecurity
case SourceDeprecation:
*t = SourceDeprecation
case SourceWorker:
*t = SourceWorker
case SourceViolation:
*t = SourceViolation
case SourceIntervention:
*t = SourceIntervention
case SourceRecommendation:
*t = SourceRecommendation
case SourceOther:
*t = SourceOther
default:
in.AddError(errors.New("unknown Source value"))
}
}
|
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/api.go#L114-L147
|
func (da *Cedar) Delete(key []byte) error {
// if the path does not exist, or the end is not a leaf, nothing to delete
to, err := da.Jump(key, 0)
if err != nil {
return ErrNoPath
}
if da.Array[to].Value < 0 {
base := da.Array[to].base()
if da.Array[base].Check == to {
to = base
}
}
for to > 0 {
from := da.Array[to].Check
base := da.Array[from].base()
label := byte(to ^ base)
// if `to` has sibling, remove `to` from the sibling list, then stop
if da.Ninfos[to].Sibling != 0 || da.Ninfos[from].Child != label {
// delete the label from the child ring first
da.popSibling(from, base, label)
// then release the current node `to` to the empty node ring
da.pushEnode(to)
break
}
// otherwise, just release the current node `to` to the empty node ring
da.pushEnode(to)
// then check its parent node
to = from
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/leader.go#L97-L121
|
func (fs *FollowerStats) Succ(d time.Duration) {
fs.Lock()
defer fs.Unlock()
total := float64(fs.Counts.Success) * fs.Latency.Average
totalSquare := float64(fs.Counts.Success) * fs.Latency.averageSquare
fs.Counts.Success++
fs.Latency.Current = float64(d) / (1000000.0)
if fs.Latency.Current > fs.Latency.Maximum {
fs.Latency.Maximum = fs.Latency.Current
}
if fs.Latency.Current < fs.Latency.Minimum {
fs.Latency.Minimum = fs.Latency.Current
}
fs.Latency.Average = (total + fs.Latency.Current) / float64(fs.Counts.Success)
fs.Latency.averageSquare = (totalSquare + fs.Latency.Current*fs.Latency.Current) / float64(fs.Counts.Success)
// sdv = sqrt(avg(x^2) - avg(x)^2)
fs.Latency.StandardDeviation = math.Sqrt(fs.Latency.averageSquare - fs.Latency.Average*fs.Latency.Average)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L400-L421
|
func raftMaybeBootstrap(
conf *raft.Config,
logs *raftboltdb.BoltStore,
snaps raft.SnapshotStore,
trans raft.Transport) error {
// First check if we were already bootstrapped.
hasExistingState, err := raft.HasExistingState(logs, logs, snaps)
if err != nil {
return errors.Wrap(err, "failed to check if raft has existing state")
}
if hasExistingState {
return nil
}
server := raft.Server{
ID: conf.LocalID,
Address: trans.LocalAddr(),
}
configuration := raft.Configuration{
Servers: []raft.Server{server},
}
return raft.BootstrapCluster(conf, logs, logs, snaps, trans, configuration)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L386-L447
|
func (loc *ApplicationLocator) Create(name string, shortDescription string, options rsapi.APIParams) (*ApplicationLocator, error) {
var res *ApplicationLocator
if name == "" {
return res, fmt.Errorf("name is required")
}
if shortDescription == "" {
return res, fmt.Errorf("shortDescription is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"name": name,
"short_description": shortDescription,
}
var compiledCatOpt = options["compiled_cat"]
if compiledCatOpt != nil {
p["compiled_cat"] = compiledCatOpt
}
var longDescriptionOpt = options["long_description"]
if longDescriptionOpt != nil {
p["long_description"] = longDescriptionOpt
}
var scheduleRequiredOpt = options["schedule_required"]
if scheduleRequiredOpt != nil {
p["schedule_required"] = scheduleRequiredOpt
}
var schedulesOpt = options["schedules"]
if schedulesOpt != nil {
p["schedules"] = schedulesOpt
}
var templateHrefOpt = options["template_href"]
if templateHrefOpt != nil {
p["template_href"] = templateHrefOpt
}
uri, err := loc.ActionPath("Application", "create")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
location := resp.Header.Get("Location")
if len(location) == 0 {
return res, fmt.Errorf("Missing location header in response")
} else {
return &ApplicationLocator{Href(location), loc.api}, nil
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/encryption.go#L45-L55
|
func LoadCert(dir string) (*shared.CertInfo, error) {
prefix := "server"
if shared.PathExists(filepath.Join(dir, "cluster.crt")) {
prefix = "cluster"
}
cert, err := shared.KeyPairAndCA(dir, prefix, shared.CertServer)
if err != nil {
return nil, errors.Wrap(err, "failed to load TLS certificate")
}
return cert, nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/memcache/memcache_service.pb.go#L334-L339
|
func (m *AppOverride) GetNumMemcachegBackends() int32 {
if m != nil && m.NumMemcachegBackends != nil {
return *m.NumMemcachegBackends
}
return 0
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L9476-L9483
|
func (r *RightScriptAttachment) Locator(api *API) *RightScriptAttachmentLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.RightScriptAttachmentLocator(l["href"])
}
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L149-L151
|
func (p *StartPreciseCoverageParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStartPreciseCoverage, p, nil)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/patch_apps_app_parameters.go#L128-L131
|
func (o *PatchAppsAppParams) WithBody(body *models.AppWrapper) *PatchAppsAppParams {
o.SetBody(body)
return o
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/informers/externalversions/tsuru/v1/interface.go#L33-L35
|
func (v *version) Apps() AppInformer {
return &appInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/informers/externalversions/prowjobs/v1/prowjob.go#L50-L52
|
func NewProwJobInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredProwJobInformer(client, namespace, resyncPeriod, indexers, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/easyjson.go#L896-L900
|
func (v Node) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAccessibility4(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxtype.go#L603-L605
|
func (p CvPoint2D32f) ToPoint() Point2D32f {
return Point2D32f{float32(p.x), float32(p.y)}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L172-L197
|
func GenerateRule(repo Repo) *rule.Rule {
r := rule.NewRule("go_repository", repo.Name)
if repo.Commit != "" {
r.SetAttr("commit", repo.Commit)
}
if repo.Tag != "" {
r.SetAttr("tag", repo.Tag)
}
r.SetAttr("importpath", repo.GoPrefix)
if repo.Remote != "" {
r.SetAttr("remote", repo.Remote)
}
if repo.VCS != "" {
r.SetAttr("vcs", repo.VCS)
}
if repo.Version != "" {
r.SetAttr("version", repo.Version)
}
if repo.Sum != "" {
r.SetAttr("sum", repo.Sum)
}
if repo.Replace != "" {
r.SetAttr("replace", repo.Replace)
}
return r
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L39-L44
|
func (f *Filtered) WithFilters(filters ...Filter) *Filtered {
return &Filtered{
Interface: f.Interface,
filters: append(f.filters, filters...),
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config.go#L619-L665
|
func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
token = cfg.InitialClusterToken
switch {
case cfg.Durl != "":
urlsmap = types.URLsMap{}
// If using discovery, generate a temporary cluster based on
// self's advertised peer URLs
urlsmap[cfg.Name] = cfg.APUrls
token = cfg.Durl
case cfg.DNSCluster != "":
clusterStrs, cerr := cfg.GetDNSClusterNames()
lg := cfg.logger
if cerr != nil {
if lg != nil {
lg.Warn("failed to resolve during SRV discovery", zap.Error(cerr))
} else {
plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
}
return nil, "", cerr
}
for _, s := range clusterStrs {
if lg != nil {
lg.Info("got bootstrap from DNS for etcd-server", zap.String("node", s))
} else {
plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
}
}
clusterStr := strings.Join(clusterStrs, ",")
if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.TrustedCAFile == "" {
cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
}
urlsmap, err = types.NewURLsMap(clusterStr)
// only etcd member must belong to the discovered cluster.
// proxy does not need to belong to the discovered cluster.
if which == "etcd" {
if _, ok := urlsmap[cfg.Name]; !ok {
return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
}
}
default:
// We're statically configured, and cluster has appropriately been set.
urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
}
return urlsmap, token, err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1763-L1775
|
func (u *Unordered) PutFile(path string, hash []byte, size int64, blockRefs ...*pfs.BlockRef) {
path = join(u.root, path)
nodeProto := &NodeProto{
Name: base(path),
Hash: hash,
SubtreeSize: size,
FileNode: &FileNodeProto{
BlockRefs: blockRefs,
},
}
u.fs[path] = nodeProto
u.createParents(path)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L85-L95
|
func Send(response http.ResponseWriter, blobKey appengine.BlobKey) {
hdr := response.Header()
hdr.Set("X-AppEngine-BlobKey", string(blobKey))
if hdr.Get("Content-Type") == "" {
// This value is known to dev_appserver to mean automatic.
// In production this is remapped to the empty value which
// means automatic.
hdr.Set("Content-Type", "application/vnd.google.appengine.auto")
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L146-L215
|
func (r *Raft) runFollower() {
didWarn := false
r.logger.Info(fmt.Sprintf("%v entering Follower state (Leader: %q)", r, r.Leader()))
metrics.IncrCounter([]string{"raft", "state", "follower"}, 1)
heartbeatTimer := randomTimeout(r.conf.HeartbeatTimeout)
for {
select {
case rpc := <-r.rpcCh:
r.processRPC(rpc)
case c := <-r.configurationChangeCh:
// Reject any operations since we are not the leader
c.respond(ErrNotLeader)
case a := <-r.applyCh:
// Reject any operations since we are not the leader
a.respond(ErrNotLeader)
case v := <-r.verifyCh:
// Reject any operations since we are not the leader
v.respond(ErrNotLeader)
case r := <-r.userRestoreCh:
// Reject any restores since we are not the leader
r.respond(ErrNotLeader)
case c := <-r.configurationsCh:
c.configurations = r.configurations.Clone()
c.respond(nil)
case b := <-r.bootstrapCh:
b.respond(r.liveBootstrap(b.configuration))
case <-heartbeatTimer:
// Restart the heartbeat timer
heartbeatTimer = randomTimeout(r.conf.HeartbeatTimeout)
// Check if we have had a successful contact
lastContact := r.LastContact()
if time.Now().Sub(lastContact) < r.conf.HeartbeatTimeout {
continue
}
// Heartbeat failed! Transition to the candidate state
lastLeader := r.Leader()
r.setLeader("")
if r.configurations.latestIndex == 0 {
if !didWarn {
r.logger.Warn("no known peers, aborting election")
didWarn = true
}
} else if r.configurations.latestIndex == r.configurations.committedIndex &&
!hasVote(r.configurations.latest, r.localID) {
if !didWarn {
r.logger.Warn("not part of stable configuration, aborting election")
didWarn = true
}
} else {
r.logger.Warn(fmt.Sprintf("Heartbeat timeout from %q reached, starting election", lastLeader))
metrics.IncrCounter([]string{"raft", "transition", "heartbeat_timeout"}, 1)
r.setState(Candidate)
return
}
case <-r.shutdownCh:
return
}
}
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L393-L403
|
func (g *WithT) Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion {
timeoutInterval := defaultConsistentlyDuration
pollingInterval := defaultConsistentlyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/decorate/podspec.go#L214-L235
|
func sshVolume(secret string) (coreapi.Volume, coreapi.VolumeMount) {
var sshKeyMode int32 = 0400 // this is octal, so symbolic ref is `u+r`
name := strings.Join([]string{"ssh-keys", secret}, "-")
mountPath := path.Join("/secrets/ssh", secret)
v := coreapi.Volume{
Name: name,
VolumeSource: coreapi.VolumeSource{
Secret: &coreapi.SecretVolumeSource{
SecretName: secret,
DefaultMode: &sshKeyMode,
},
},
}
vm := coreapi.VolumeMount{
Name: name,
MountPath: mountPath,
ReadOnly: true,
}
return v, vm
}
|
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L178-L188
|
func checkLine(line string) (string, string, bool) {
key := ""
value := ""
sp := strings.SplitN(line, "=", 2)
if len(sp) != 2 {
return key, value, false
}
key = strings.TrimSpace(sp[0])
value = strings.TrimSpace(sp[1])
return key, value, true
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L257-L267
|
func FileSequence_New_Pad(frange *C.char, padStyle C.int) (FileSeqId, Error) {
style := fileseq.PadStyle(padStyle)
fs, e := fileseq.NewFileSequencePad(C.GoString(frange), style)
if e != nil {
// err string is freed by caller
return 0, C.CString(e.Error())
}
id := sFileSeqs.Add(fs)
return id, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L711-L725
|
func AADestroy(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAdmin {
return nil
}
if state.OS.AppArmorStacking && !state.OS.AppArmorStacked {
p := path.Join("/sys/kernel/security/apparmor/policy/namespaces", AANamespace(c))
if err := os.Remove(p); err != nil {
logger.Error("Error removing apparmor namespace", log.Ctx{"err": err, "ns": p})
}
}
return runApparmor(APPARMOR_CMD_UNLOAD, c)
}
|
https://github.com/intelsdi-x/gomit/blob/286c3ad6599724faed681cd18a9ff595b00d9f3f/event_controller.go#L114-L117
|
func (e *EventController) IsHandlerRegistered(n string) bool {
_, x := e.Handlers[n]
return x
}
|
https://github.com/brankas/sentinel/blob/0ff081867c31a45cb71f5976ea6144fd06a557b5/opts.go#L68-L80
|
func Ignore(ignore ...func(error) bool) Option {
return func(s *Sentinel) error {
s.Lock()
defer s.Unlock()
if s.started {
return ErrAlreadyStarted
}
s.ignoreErrors = append(s.ignoreErrors, ignore...)
return nil
}
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/struct_filter.go#L110-L127
|
func (ft fieldTree) matchPrefix(p cmp.Path) bool {
for _, ps := range p {
switch ps := ps.(type) {
case cmp.StructField:
ft = ft.sub[ps.Name()]
if ft.ok {
return true
}
if len(ft.sub) == 0 {
return false
}
case cmp.Indirect:
default:
return false
}
}
return false
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/resource_analysis.go#L9-L88
|
func (a *APIAnalyzer) AnalyzeResource(name string, res map[string]interface{}, desc *gen.APIDescriptor) error {
name = inflect.Singularize(name)
resource := gen.Resource{Name: name, ClientName: a.ClientName}
// Description
if d, ok := res["description"]; ok {
resource.Description = removeBlankLines(d.(string))
}
// Attributes
hasHref := false
identifier := ""
attributes := []*gen.Attribute{}
links := map[string]string{}
m, ok := res["media_type"].(string)
if ok {
t, ok := a.RawTypes[m]
if ok {
attrs, ok := t["attributes"].(map[string]interface{})
if ok {
attributes = make([]*gen.Attribute, len(attrs))
for idx, n := range sortedKeys(attrs) {
if n == "href" {
hasHref = true
}
param, err := a.AnalyzeAttribute(n, n, attrs[n].(map[string]interface{}))
if err != nil {
return err
}
attributes[idx] = &gen.Attribute{n, inflect.Camelize(n), param.Signature()}
}
// Extract links
if l, ok := attrs["links"].(map[string]interface{}); ok {
if ltype, ok := l["type"].(map[string]interface{}); ok {
if lattrs, ok := ltype["attributes"].(map[string]interface{}); ok {
links = make(map[string]string, len(lattrs))
for n, d := range lattrs {
if dm, ok := d.(map[string]interface{}); ok {
if desc, ok := dm["description"].(string); ok {
links[n] = desc
} else {
links[n] = "" // No description in Skeletor :(
}
}
}
}
}
}
}
// Extract media type identifier
if id, ok := t["identifier"]; ok { // Praxis
identifier = id.(string)
} else if id, ok := t["mime_type"]; ok { // Skeletor
identifier = id.(string)
}
}
}
resource.Attributes = attributes
resource.Identifier = identifier
resource.Links = links
if hasHref {
resource.LocatorFunc = locatorFunc(name)
}
// Actions
actions, err := a.AnalyzeActions(name, res)
if err != nil {
return err
}
resource.Actions = actions
// Name and done
resName := toGoTypeName(name)
desc.Resources[resName] = &resource
desc.ResourceNames = append(desc.ResourceNames, resName)
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry.go#L57-L77
|
func isSafeRetryImmutableRPC(err error) bool {
eErr := rpctypes.Error(err)
if serverErr, ok := eErr.(rpctypes.EtcdError); ok && serverErr.Code() != codes.Unavailable {
// interrupted by non-transient server-side or gRPC-side error
// client cannot handle itself (e.g. rpctypes.ErrCompacted)
return false
}
// only retry if unavailable
ev, ok := status.FromError(err)
if !ok {
// all errors from RPC is typed "grpc/status.(*statusError)"
// (ref. https://github.com/grpc/grpc-go/pull/1782)
//
// if the error type is not "grpc/status.(*statusError)",
// it could be from "Dial"
// TODO: do not retry for now
// ref. https://github.com/grpc/grpc-go/issues/1581
return false
}
return ev.Code() == codes.Unavailable
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_transport.go#L50-L61
|
func NewInmemTransportWithTimeout(addr ServerAddress, timeout time.Duration) (ServerAddress, *InmemTransport) {
if string(addr) == "" {
addr = NewInmemAddr()
}
trans := &InmemTransport{
consumerCh: make(chan RPC, 16),
localAddr: addr,
peers: make(map[ServerAddress]*InmemTransport),
timeout: timeout,
}
return addr, trans
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L193-L206
|
func (b *Bucket) Delete(path string) error {
if err := b.delete(path); err != nil {
return err
}
// try to delete md5 file
if b.Md5Check {
if err := b.delete(fmt.Sprintf("/.md5/%s.md5", path)); err != nil {
return err
}
}
logger.Printf("%s deleted from %s\n", path, b.Name)
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L92-L95
|
func RegisterStatusEventHandler(name string, fn StatusEventHandler, help HelpProvider) {
pluginHelp[name] = help
statusEventHandlers[name] = fn
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/request.go#L72-L77
|
func (c *Client) ListRequests() (*Requests, error) {
url := "/requests" + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Requests{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L71-L75
|
func (v *UndoParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom(&r, v)
return r.Error()
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/security/nonce.go#L78-L82
|
func Age(age time.Duration) Option {
return Option{func(o *options) {
o.age = age
}}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2760-L2764
|
func (v SearchInResponseBodyReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork20(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/job.go#L93-L129
|
func Enqueue(store *coal.SubStore, name string, data Model, delay time.Duration) (*Job, error) {
// set default data
if data == nil {
data = bson.M{}
}
// get time
now := time.Now()
// prepare job
job := coal.Init(&Job{
Name: name,
Status: StatusEnqueued,
Created: now,
Available: now.Add(delay),
}).(*Job)
// marshall data
raw, err := bson.Marshal(data)
if err != nil {
return nil, err
}
// marshall into job
err = bson.Unmarshal(raw, &job.Data)
if err != nil {
return nil, err
}
// insert job
err = store.C(job).Insert(job)
if err != nil {
return nil, err
}
return job, nil
}
|
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L101-L113
|
func (api *TelegramBotAPI) NewOutgoingPhotoResend(recipient Recipient, fileID string) *OutgoingPhoto {
return &OutgoingPhoto{
outgoingMessageBase: outgoingMessageBase{
outgoingBase: outgoingBase{
api: api,
Recipient: recipient,
},
},
outgoingFileBase: outgoingFileBase{
fileID: fileID,
},
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L380-L430
|
func (r *Raft) pipelineReplicate(s *followerReplication) error {
// Create a new pipeline
pipeline, err := r.trans.AppendEntriesPipeline(s.peer.ID, s.peer.Address)
if err != nil {
return err
}
defer pipeline.Close()
// Log start and stop of pipeline
r.logger.Info(fmt.Sprintf("pipelining replication to peer %v", s.peer))
defer r.logger.Info(fmt.Sprintf("aborting pipeline replication to peer %v", s.peer))
// Create a shutdown and finish channel
stopCh := make(chan struct{})
finishCh := make(chan struct{})
// Start a dedicated decoder
r.goFunc(func() { r.pipelineDecode(s, pipeline, stopCh, finishCh) })
// Start pipeline sends at the last good nextIndex
nextIndex := s.nextIndex
shouldStop := false
SEND:
for !shouldStop {
select {
case <-finishCh:
break SEND
case maxIndex := <-s.stopCh:
// Make a best effort to replicate up to this index
if maxIndex > 0 {
r.pipelineSend(s, pipeline, &nextIndex, maxIndex)
}
break SEND
case <-s.triggerCh:
lastLogIdx, _ := r.getLastLog()
shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx)
case <-randomTimeout(r.conf.CommitTimeout):
lastLogIdx, _ := r.getLastLog()
shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx)
}
}
// Stop our decoder, and wait for it to finish
close(stopCh)
select {
case <-finishCh:
case <-r.shutdownCh:
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.go#L67-L95
|
func (c *ClusterTx) ProjectMap() (map[int64]string, error) {
stmt := "SELECT id, name FROM projects"
rows, err := c.tx.Query(stmt)
if err != nil {
return nil, err
}
defer rows.Close()
result := map[int64]string{}
for i := 0; rows.Next(); i++ {
var id int64
var name string
err := rows.Scan(&id, &name)
if err != nil {
return nil, err
}
result[id] = name
}
err = rows.Err()
if err != nil {
return nil, err
}
return result, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/kvstore.go#L111-L150
|
func NewStore(lg *zap.Logger, b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) *store {
s := &store{
b: b,
ig: ig,
kvindex: newTreeIndex(lg),
le: le,
currentRev: 1,
compactMainRev: -1,
bytesBuf8: make([]byte, 8),
fifoSched: schedule.NewFIFOScheduler(),
stopc: make(chan struct{}),
lg: lg,
}
s.ReadView = &readView{s}
s.WriteView = &writeView{s}
if s.le != nil {
s.le.SetRangeDeleter(func() lease.TxnDelete { return s.Write() })
}
tx := s.b.BatchTx()
tx.Lock()
tx.UnsafeCreateBucket(keyBucketName)
tx.UnsafeCreateBucket(metaBucketName)
tx.Unlock()
s.b.ForceCommit()
s.mu.Lock()
defer s.mu.Unlock()
if err := s.restore(); err != nil {
// TODO: return the error instead of panic here?
panic("failed to recover store from backend")
}
return s
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L13989-L13996
|
func (r *User) Locator(api *API) *UserLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.UserLocator(l["href"])
}
}
return nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/tcp_transport.go#L110-L116
|
func (t *TCPStreamLayer) Addr() net.Addr {
// Use an advertise addr if provided
if t.advertise != nil {
return t.advertise
}
return t.listener.Addr()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/grpc1.7-health.go#L269-L277
|
func (b *GRPC17Health) NeedUpdate() bool {
// updating notifyCh can trigger new connections,
// need update addrs if all connections are down
// or addrs does not include pinAddr.
b.mu.RLock()
update := !hasAddr(b.addrs, b.pinAddr)
b.mu.RUnlock()
return update
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L550-L556
|
func copyHiddenHeaders(from map[string]bool) (to map[string]bool) {
to = make(map[string]bool)
for k, v := range from {
to[k] = v
}
return
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L135-L144
|
func simplifyContentType(contentType string) string {
if contentType == "" {
return contentType
}
mimeType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return ""
}
return mimeType
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L826-L828
|
func (seq *Seq) PushFront(element unsafe.Pointer) unsafe.Pointer {
return unsafe.Pointer((C.cvSeqPushFront((*C.struct_CvSeq)(seq), element)))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/types.go#L133-L143
|
func (t *AuthChallengeSource) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch AuthChallengeSource(in.String()) {
case AuthChallengeSourceServer:
*t = AuthChallengeSourceServer
case AuthChallengeSourceProxy:
*t = AuthChallengeSourceProxy
default:
in.AddError(errors.New("unknown AuthChallengeSource value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L665-L669
|
func (v RareBooleanData) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/main_activateifneeded.go#L156-L180
|
func sqliteDirectAccess(conn *sqlite3.SQLiteConn) error {
// Ensure journal mode is set to WAL, as this is a requirement for
// replication.
_, err := conn.Exec("PRAGMA journal_mode=wal", nil)
if err != nil {
return err
}
// Ensure we don't truncate or checkpoint the WAL on exit, as this
// would bork replication which must be in full control of the WAL
// file.
_, err = conn.Exec("PRAGMA journal_size_limit=-1", nil)
if err != nil {
return err
}
// Ensure WAL autocheckpoint is disabled, since checkpoints are
// triggered explicitly by dqlite.
_, err = conn.Exec("PRAGMA wal_autocheckpoint=0", nil)
if err != nil {
return err
}
return nil
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/sessionInit.go#L22-L64
|
func session(ctx *Context) {
var cookie *http.Cookie
cookies := ctx.Request.Cookies()
if len(cookies) == 0 {
ctx.Next()
return
}
for _, v := range cookies {
if v.Name == httpCookie.Name {
cookie = v
break
}
}
if cookie == nil {
ctx.Next()
return
}
sid := cookie.Value
store, err := provider.Get(sid)
if err != nil {
log.WithFields(log.Fields{"sid": sid, "err": err}).Warnln("读取session失败")
ctx.Fail(err)
return
}
if len(store.Values) > 0 {
//err := provider.refresh(store)
err := provider.UpExpire(sid)
if err != nil {
log.WithFields(log.Fields{"sid": sid, "err": err}).Warnln("刷新session失败")
ctx.Fail(err)
return
}
cookie := httpCookie
cookie.Value = sid
ctx.Data["session"] = store
ctx.Data["Sid"] = sid
http.SetCookie(ctx.ResponseWriter, &cookie)
}
ctx.Next()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L120-L122
|
func (f *FakeClient) ListIssueComments(owner, repo string, number int) ([]github.IssueComment, error) {
return append([]github.IssueComment{}, f.IssueComments[number]...), nil
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L197-L201
|
func StripPunctuation(s string) string {
s = stripPuncRe.ReplaceAllString(s, "")
s = nWhitespaceRe.ReplaceAllString(s, " ")
return s
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L150-L157
|
func BatchSpec(p config.Presubmit, refs prowapi.Refs) prowapi.ProwJobSpec {
pjs := specFromJobBase(p.JobBase)
pjs.Type = prowapi.BatchJob
pjs.Context = p.Context
pjs.Refs = completePrimaryRefs(refs, p.JobBase)
return pjs
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L754-L759
|
func SetCookie(name string, value string) *SetCookieParams {
return &SetCookieParams{
Name: name,
Value: value,
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/require/require.go#L336-L355
|
func NoErrorWithinTRetry(tb testing.TB, t time.Duration, f func() error, msgAndArgs ...interface{}) {
tb.Helper()
doneCh := make(chan struct{})
timeout := false
var err error
go func() {
for !timeout {
if err = f(); err == nil {
close(doneCh)
break
}
}
}()
select {
case <-doneCh:
case <-time.After(t):
timeout = true
fatal(tb, msgAndArgs, "operation did not finish within %s - last error: %v", t.String(), err)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L131-L133
|
func (p *RemoveDOMStorageItemParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandRemoveDOMStorageItem, p, nil)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/dir_unix.go#L45-L80
|
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (*directoryLockGuard, error) {
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absPidFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, errors.Wrap(err, "cannot get absolute path for pid lock file")
}
f, err := os.Open(dirPath)
if err != nil {
return nil, errors.Wrapf(err, "cannot open directory %q", dirPath)
}
opts := unix.LOCK_EX | unix.LOCK_NB
if readOnly {
opts = unix.LOCK_SH | unix.LOCK_NB
}
err = unix.Flock(int(f.Fd()), opts)
if err != nil {
f.Close()
return nil, errors.Wrapf(err,
"Cannot acquire directory lock on %q. Another process is using this Badger database.",
dirPath)
}
if !readOnly {
// Yes, we happily overwrite a pre-existing pid file. We're the
// only read-write badger process using this directory.
err = ioutil.WriteFile(absPidFilePath, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0666)
if err != nil {
f.Close()
return nil, errors.Wrapf(err,
"Cannot write pid file %q", absPidFilePath)
}
}
return &directoryLockGuard{f, absPidFilePath, readOnly}, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.