_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L6865-L6867
|
func (api *API) NetworkOptionGroupAttachmentLocator(href string) *NetworkOptionGroupAttachmentLocator {
return &NetworkOptionGroupAttachmentLocator{Href(href), api}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L286-L293
|
func (l *PeerList) updatePeer(ps *peerScore, newScore uint64) {
if ps.score == newScore {
return
}
ps.score = newScore
l.peerHeap.updatePeer(ps)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L6199-L6203
|
func (v *EventResourceChangedPriority) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork49(&r, v)
return r.Error()
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/filehandler.go#L94-L99
|
func (h *RotatingFileHandler) Close() error {
if h.fd != nil {
return h.fd.Close()
}
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/lease/lessor.go#L351-L401
|
func (le *lessor) Renew(id LeaseID) (int64, error) {
le.mu.RLock()
if !le.isPrimary() {
// forward renew request to primary instead of returning error.
le.mu.RUnlock()
return -1, ErrNotPrimary
}
demotec := le.demotec
l := le.leaseMap[id]
if l == nil {
le.mu.RUnlock()
return -1, ErrLeaseNotFound
}
// Clear remaining TTL when we renew if it is set
clearRemainingTTL := le.cp != nil && l.remainingTTL > 0
le.mu.RUnlock()
if l.expired() {
select {
// A expired lease might be pending for revoking or going through
// quorum to be revoked. To be accurate, renew request must wait for the
// deletion to complete.
case <-l.revokec:
return -1, ErrLeaseNotFound
// The expired lease might fail to be revoked if the primary changes.
// The caller will retry on ErrNotPrimary.
case <-demotec:
return -1, ErrNotPrimary
case <-le.stopC:
return -1, ErrNotPrimary
}
}
// Clear remaining TTL when we renew if it is set
// By applying a RAFT entry only when the remainingTTL is already set, we limit the number
// of RAFT entries written per lease to a max of 2 per checkpoint interval.
if clearRemainingTTL {
le.cp(context.Background(), &pb.LeaseCheckpointRequest{Checkpoints: []*pb.LeaseCheckpoint{{ID: int64(l.ID), Remaining_TTL: 0}}})
}
le.mu.Lock()
l.refresh(0)
item := &LeaseWithTime{id: l.ID, time: l.expiry.UnixNano()}
heap.Push(&le.leaseHeap, item)
le.mu.Unlock()
leaseRenewed.Inc()
return l.ttl, nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/font.go#L193-L216
|
func (cache *SyncFolderFontCache) Load(fontData FontData) (font *truetype.Font, err error) {
cache.RLock()
font = cache.fonts[cache.namer(fontData)]
cache.RUnlock()
if font != nil {
return font, nil
}
var data []byte
var file = cache.namer(fontData)
if data, err = ioutil.ReadFile(filepath.Join(cache.folder, file)); err != nil {
return
}
if font, err = truetype.Parse(data); err != nil {
return
}
cache.Lock()
cache.fonts[file] = font
cache.Unlock()
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L255-L264
|
func (c *ClusterTx) OperationNodes(project string) ([]string, error) {
stmt := `
SELECT DISTINCT nodes.address
FROM operations
LEFT OUTER JOIN projects ON projects.id = operations.project_id
JOIN nodes ON nodes.id = operations.node_id
WHERE projects.name = ? OR operations.project_id IS NULL
`
return query.SelectStrings(c.tx, stmt, project)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1038-L1051
|
func (c APIClient) GetFile(repoName string, commitID string, path string, offset int64, size int64, writer io.Writer) error {
if c.limiter != nil {
c.limiter.Acquire()
defer c.limiter.Release()
}
apiGetFileClient, err := c.getFile(repoName, commitID, path, offset, size)
if err != nil {
return grpcutil.ScrubGRPC(err)
}
if err := grpcutil.WriteFromStreamingBytesClient(apiGetFileClient, writer); err != nil {
return grpcutil.ScrubGRPC(err)
}
return nil
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L308-L314
|
func (g *Glg) GetCurrentMode(level LEVEL) MODE {
l, ok := g.logger.Load(level)
if ok {
return l.(*logger).mode
}
return NONE
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1221-L1223
|
func (r *Network) Locator(api *API) *NetworkLocator {
return api.NetworkLocator(r.Href)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gerrit/client/client.go#L193-L205
|
func (c *Client) QueryChanges(lastUpdate time.Time, rateLimit int) map[string][]ChangeInfo {
result := map[string][]ChangeInfo{}
for _, h := range c.handlers {
changes := h.queryAllChanges(lastUpdate, rateLimit)
if len(changes) > 0 {
result[h.instance] = []ChangeInfo{}
for _, change := range changes {
result[h.instance] = append(result[h.instance], change)
}
}
}
return result
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L190-L195
|
func (o *ListBoolOption) Set(value string) error {
val := BoolOption{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L199-L249
|
func fileNameInfo(path_ string) fileInfo {
name := filepath.Base(path_)
var ext ext
switch path.Ext(name) {
case ".go":
ext = goExt
case ".c", ".cc", ".cpp", ".cxx", ".m", ".mm":
ext = cExt
case ".h", ".hh", ".hpp", ".hxx":
ext = hExt
case ".s":
ext = sExt
case ".S":
ext = csExt
case ".proto":
ext = protoExt
default:
ext = unknownExt
}
if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
ext = unknownExt
}
// Determine test, goos, and goarch. This is intended to match the logic
// in goodOSArchFile in go/build.
var isTest bool
var goos, goarch string
l := strings.Split(name[:len(name)-len(path.Ext(name))], "_")
if len(l) >= 2 && l[len(l)-1] == "test" {
isTest = ext == goExt
l = l[:len(l)-1]
}
switch {
case len(l) >= 3 && rule.KnownOSSet[l[len(l)-2]] && rule.KnownArchSet[l[len(l)-1]]:
goos = l[len(l)-2]
goarch = l[len(l)-1]
case len(l) >= 2 && rule.KnownOSSet[l[len(l)-1]]:
goos = l[len(l)-1]
case len(l) >= 2 && rule.KnownArchSet[l[len(l)-1]]:
goarch = l[len(l)-1]
}
return fileInfo{
path: path_,
name: name,
ext: ext,
isTest: isTest,
goos: goos,
goarch: goarch,
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L687-L835
|
func RegisterKVHandlerClient(ctx context.Context, mux *runtime.ServeMux, client etcdserverpb.KVClient) error {
mux.Handle("POST", pattern_KV_Range_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_KV_Range_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_KV_Range_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_KV_Put_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_KV_Put_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_KV_Put_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_KV_DeleteRange_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_KV_DeleteRange_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_KV_DeleteRange_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_KV_Txn_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_KV_Txn_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_KV_Txn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_KV_Compact_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_KV_Compact_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_KV_Compact_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L702-L704
|
func (t InterceptionStage) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L268-L271
|
func (p HighlightRectParams) WithOutlineColor(outlineColor *cdp.RGBA) *HighlightRectParams {
p.OutlineColor = outlineColor
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/raftexample/raft.go#L227-L250
|
func (rc *raftNode) replayWAL() *wal.WAL {
log.Printf("replaying WAL of member %d", rc.id)
snapshot := rc.loadSnapshot()
w := rc.openWAL(snapshot)
_, st, ents, err := w.ReadAll()
if err != nil {
log.Fatalf("raftexample: failed to read WAL (%v)", err)
}
rc.raftStorage = raft.NewMemoryStorage()
if snapshot != nil {
rc.raftStorage.ApplySnapshot(*snapshot)
}
rc.raftStorage.SetHardState(st)
// append to storage so raft starts at the right place in log
rc.raftStorage.Append(ents)
// send nil once lastIndex is published so client knows commit channel is current
if len(ents) > 0 {
rc.lastIndex = ents[len(ents)-1].Index
} else {
rc.commitC <- nil
}
return w
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api.go#L594-L647
|
func (c *context) flushLog(force bool) (flushed bool) {
c.pendingLogs.Lock()
// Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious.
n, rem := 0, 30<<20
for ; n < len(c.pendingLogs.lines); n++ {
ll := c.pendingLogs.lines[n]
// Each log line will require about 3 bytes of overhead.
nb := proto.Size(ll) + 3
if nb > rem {
break
}
rem -= nb
}
lines := c.pendingLogs.lines[:n]
c.pendingLogs.lines = c.pendingLogs.lines[n:]
c.pendingLogs.Unlock()
if len(lines) == 0 && !force {
// Nothing to flush.
return false
}
rescueLogs := false
defer func() {
if rescueLogs {
c.pendingLogs.Lock()
c.pendingLogs.lines = append(lines, c.pendingLogs.lines...)
c.pendingLogs.Unlock()
}
}()
buf, err := proto.Marshal(&logpb.UserAppLogGroup{
LogLine: lines,
})
if err != nil {
log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err)
rescueLogs = true
return false
}
req := &logpb.FlushRequest{
Logs: buf,
}
res := &basepb.VoidProto{}
c.pendingLogs.Lock()
c.pendingLogs.flushes++
c.pendingLogs.Unlock()
if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil {
log.Printf("internal.flushLog: Flush RPC: %v", err)
rescueLogs = true
return false
}
return true
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L327-L333
|
func encodeConfiguration(configuration Configuration) []byte {
buf, err := encodeMsgPack(configuration)
if err != nil {
panic(fmt.Errorf("failed to encode configuration: %v", err))
}
return buf.Bytes()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4239-L4248
|
func (u OperationResultTr) GetManageDataResult() (result ManageDataResult, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "ManageDataResult" {
result = *u.ManageDataResult
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L413-L415
|
func (t *CaptureSnapshotFormat) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/cache.go#L15-L18
|
func newBICLocationReference(ref dockerReference) types.BICLocationReference {
// Blobs are scoped to repositories (the tag/digest are not necessary to reuse a blob).
return types.BICLocationReference{Opaque: ref.ref.Name()}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L323-L326
|
func (p EvaluateParams) WithObjectGroup(objectGroup string) *EvaluateParams {
p.ObjectGroup = objectGroup
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L713-L722
|
func (p *SetStyleTextsParams) Do(ctx context.Context) (styles []*Style, err error) {
// execute
var res SetStyleTextsReturns
err = cdp.Execute(ctx, CommandSetStyleTexts, p, &res)
if err != nil {
return nil, err
}
return res.Styles, nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L27-L34
|
func Wrap(ctx log.Interface, namespaces ...string) *Namespaced {
return &Namespaced{
Interface: ctx,
namespaces: &ns{
namespaces: namespaces,
},
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L589-L593
|
func (v SetPageScaleFactorParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation6(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/task/group.go#L36-L67
|
func (g *Group) Start() {
ctx := context.Background()
ctx, g.cancel = context.WithCancel(ctx)
g.wg.Add(len(g.tasks))
g.mu.Lock()
if g.running == nil {
g.running = make(map[int]bool)
}
g.mu.Unlock()
for i := range g.tasks {
g.mu.Lock()
if g.running[i] {
g.mu.Unlock()
continue
}
g.running[i] = true
task := g.tasks[i] // Local variable for the closure below.
g.mu.Unlock()
go func(i int) {
task.loop(ctx)
g.wg.Done()
g.mu.Lock()
g.running[i] = false
g.mu.Unlock()
}(i)
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/pbutil/pbutil.go#L91-L93
|
func NewReadWriter(rw io.ReadWriter) ReadWriter {
return &readWriter{r: rw, w: rw}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/snapshot.go#L69-L99
|
func (r *Raft) runSnapshots() {
for {
select {
case <-randomTimeout(r.conf.SnapshotInterval):
// Check if we should snapshot
if !r.shouldSnapshot() {
continue
}
// Trigger a snapshot
if _, err := r.takeSnapshot(); err != nil {
r.logger.Error(fmt.Sprintf("Failed to take snapshot: %v", err))
}
case future := <-r.userSnapshotCh:
// User-triggered, run immediately
id, err := r.takeSnapshot()
if err != nil {
r.logger.Error(fmt.Sprintf("Failed to take snapshot: %v", err))
} else {
future.opener = func() (*SnapshotMeta, io.ReadCloser, error) {
return r.snapshots.Open(id)
}
}
future.respond(err)
case <-r.shutdownCh:
return
}
}
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L106-L116
|
func (b *FixedSizeRingBuf) BytesTwo(makeCopy bool) (first []byte, second []byte) {
extent := b.Beg + b.Readable
if extent <= b.N {
// we fit contiguously in this buffer without wrapping to the other.
// Let second stay an empty slice.
return b.A[b.Use][b.Beg:(b.Beg + b.Readable)], second
}
return b.A[b.Use][b.Beg:b.N], b.A[b.Use][0:(extent % b.N)]
}
|
https://github.com/cloudfoundry-incubator/cf-test-helpers/blob/83791edc4b0a2d48b602088c30332063b8f02f32/helpers/app_commands.go#L25-L28
|
func CurlApp(cfg helpersinternal.CurlConfig, appName, path string, args ...string) string {
appCurler := helpersinternal.NewAppCurler(Curl, cfg)
return appCurler.CurlAndWait(cfg, appName, path, CURL_TIMEOUT, args...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/types.go#L181-L193
|
func (t *AuthChallengeResponseResponse) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch AuthChallengeResponseResponse(in.String()) {
case AuthChallengeResponseResponseDefault:
*t = AuthChallengeResponseResponseDefault
case AuthChallengeResponseResponseCancelAuth:
*t = AuthChallengeResponseResponseCancelAuth
case AuthChallengeResponseResponseProvideCredentials:
*t = AuthChallengeResponseResponseProvideCredentials
default:
in.AddError(errors.New("unknown AuthChallengeResponseResponse value"))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L82-L85
|
func (p DispatchKeyEventParams) WithCode(code string) *DispatchKeyEventParams {
p.Code = code
return &p
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/jsonp.go#L84-L90
|
func (w *jsonpResponseWriter) Flush() {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
flusher := w.ResponseWriter.(http.Flusher)
flusher.Flush()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5692-L5704
|
func (u LedgerEntryChange) ArmForSwitch(sw int32) (string, bool) {
switch LedgerEntryChangeType(sw) {
case LedgerEntryChangeTypeLedgerEntryCreated:
return "Created", true
case LedgerEntryChangeTypeLedgerEntryUpdated:
return "Updated", true
case LedgerEntryChangeTypeLedgerEntryRemoved:
return "Removed", true
case LedgerEntryChangeTypeLedgerEntryState:
return "State", true
}
return "-", false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1491-L1495
|
func (v ResetPageScaleFactorParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation16(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1906-L1917
|
func (c *Client) GetRef(org, repo, ref string) (string, error) {
c.log("GetRef", org, repo, ref)
var res struct {
Object map[string]string `json:"object"`
}
_, err := c.request(&request{
method: http.MethodGet,
path: fmt.Sprintf("/repos/%s/%s/git/refs/%s", org, repo, ref),
exitCodes: []int{200},
}, &res)
return res.Object["sha"], err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/selective_string.go#L32-L38
|
func (ss *SelectiveStringValue) Set(s string) error {
if _, ok := ss.valids[s]; ok {
ss.v = s
return nil
}
return errors.New("invalid value")
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1077-L1086
|
func (w *Writer) Index() ([]byte, error) {
buf := &bytes.Buffer{}
pbw := pbutil.NewWriter(buf)
for _, idx := range w.idxs {
if _, err := pbw.Write(idx); err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}
|
https://github.com/alecthomas/mph/blob/cf7b0cd2d9579868ec2a49493fd62b2e28bcb336/chd_builder.go#L192-L194
|
func (h *chdHasher) Table(r uint64, b []byte) uint64 {
return (hasher(b) ^ h.r[0] ^ r) % h.size
}
|
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/utils.go#L117-L134
|
func DecodeOAuth2Code(code, sharedKey string) (response Response, err error) {
object, err := jose.ParseSigned(code)
if err != nil {
return
}
output, err := object.Verify([]byte(sharedKey))
if err != nil {
return
}
base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(output)))
l, err := base64.StdEncoding.Decode(base64Text, output)
if err != nil {
return
}
response = Response{}
err = json.Unmarshal(base64Text[:l], &response)
return
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/encrypt.go#L29-L45
|
func Encrypt(text string) (string, error) {
bytes := []byte(text)
key := seekret()
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
b := encodeBase64(bytes)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], b)
return string(encodeBase64(ciphertext)), nil
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L172-L174
|
func (c *Client) AsyncQuery(pageSize int, dataset, project, queryStr string, dataChan chan Data) {
c.pagedQuery(pageSize, dataset, project, queryStr, dataChan)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L270-L301
|
func NewPipelineManifestReader(path string) (result *PipelineManifestReader, retErr error) {
result = &PipelineManifestReader{}
var pipelineReader io.Reader
if path == "-" {
pipelineReader = io.TeeReader(os.Stdin, &result.buf)
fmt.Print("Reading from stdin.\n")
} else if url, err := url.Parse(path); err == nil && url.Scheme != "" {
resp, err := http.Get(url.String())
if err != nil {
return nil, err
}
defer func() {
if err := resp.Body.Close(); err != nil && retErr == nil {
retErr = err
}
}()
rawBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
pipelineReader = io.TeeReader(strings.NewReader(string(rawBytes)), &result.buf)
} else {
rawBytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
pipelineReader = io.TeeReader(strings.NewReader(string(rawBytes)), &result.buf)
}
result.decoder = json.NewDecoder(pipelineReader)
return result, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/webhook.go#L125-L154
|
func webhookUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) error {
var webhook eventTypes.Webhook
err := ParseInput(r, &webhook)
if err != nil {
return err
}
webhook.Name = r.URL.Query().Get(":name")
ctx := permission.Context(permTypes.CtxTeam, webhook.TeamOwner)
if !permission.Check(t, permission.PermWebhookUpdate, ctx) {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeWebhook, Value: webhook.Name},
Kind: permission.PermWebhookUpdate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermWebhookReadEvents, ctx),
})
if err != nil {
return err
}
defer func() {
evt.Done(err)
}()
err = servicemanager.Webhook.Update(webhook)
if err == eventTypes.ErrWebhookNotFound {
w.WriteHeader(http.StatusNotFound)
}
return err
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L413-L426
|
func (s *FileSequence) Index(idx int) string {
if s.frameSet == nil {
return s.String()
}
frame, err := s.frameSet.Frame(idx)
if err != nil {
return ""
}
path, err := s.Frame(frame)
if err != nil {
return ""
}
return path
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/path.go#L195-L223
|
func (path *Path) VerticalFlip() *Path {
p := path.Copy()
j := 0
for _, cmd := range p.Components {
switch cmd {
case MoveToCmp, LineToCmp:
p.Points[j+1] = -p.Points[j+1]
j = j + 2
case QuadCurveToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
j = j + 4
case CubicCurveToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
p.Points[j+5] = -p.Points[j+5]
j = j + 6
case ArcToCmp:
p.Points[j+1] = -p.Points[j+1]
p.Points[j+3] = -p.Points[j+3]
p.Points[j+4] = -p.Points[j+4] // start angle
p.Points[j+5] = -p.Points[j+5] // angle
j = j + 6
case CloseCmp:
}
}
p.y = -p.y
return p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L109-L112
|
func (p ContinueInterceptedRequestParams) WithMethod(method string) *ContinueInterceptedRequestParams {
p.Method = method
return &p
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/listers/tsuru/v1/app.go#L46-L48
|
func (s *appLister) Apps(namespace string) AppNamespaceLister {
return appNamespaceLister{indexer: s.indexer, namespace: namespace}
}
|
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/parser/tterse/tterse.go#L36-L42
|
func NewStringLexer(template string) *parser.Lexer {
l := parser.NewStringLexer(template, SymbolSet)
l.SetTagStart("[%")
l.SetTagEnd("%]")
return l
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2051-L2055
|
func (v QuerySelectorAllParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom22(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L147-L167
|
func NewFromAddress(addr string, options ...Option) (*APIClient, error) {
// Apply creation options
settings := clientSettings{
maxConcurrentStreams: DefaultMaxConcurrentStreams,
dialTimeout: DefaultDialTimeout,
}
for _, option := range options {
if err := option(&settings); err != nil {
return nil, err
}
}
c := &APIClient{
addr: addr,
caCerts: settings.caCerts,
limiter: limit.New(settings.maxConcurrentStreams),
}
if err := c.connect(settings.dialTimeout); err != nil {
return nil, err
}
return c, nil
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L399-L431
|
func (c *Client) SyncQuery(dataset, project, queryStr string, maxResults int64) ([][]interface{}, error) {
service, err := c.connect()
if err != nil {
return nil, err
}
datasetRef := &bigquery.DatasetReference{
DatasetId: dataset,
ProjectId: project,
}
query := &bigquery.QueryRequest{
DefaultDataset: datasetRef,
MaxResults: maxResults,
Kind: "json",
Query: queryStr,
}
results, err := service.Jobs.Query(project, query).Do()
if err != nil {
c.printDebug("Query Error: ", err)
return nil, err
}
// credit to https://github.com/getlantern/statshub for the row building approach
numRows := int(results.TotalRows)
if numRows > int(maxResults) {
numRows = int(maxResults)
}
_, rows := c.headersAndRows(results.Schema, results.Rows)
return rows, nil
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/decode.go#L22-L31
|
func Unmarshal(b []byte, v interface{}) error {
u := unmarshalerPool.Get().(*unmarshaler)
u.reset(b)
err := (objconv.Decoder{Parser: u}).Decode(v)
u.reset(nil)
unmarshalerPool.Put(u)
return err
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L580-L625
|
func (db *DB) selectToSlice(rows *sql.Rows, t reflect.Type) (reflect.Value, error) {
columns, err := rows.Columns()
if err != nil {
return reflect.Value{}, err
}
t = t.Elem()
ptrN := 0
for ; t.Kind() == reflect.Ptr; ptrN++ {
t = t.Elem()
}
fieldIndexes := make([][]int, len(columns))
for i, column := range columns {
index := db.fieldIndexByName(t, column, nil)
if len(index) < 1 {
return reflect.Value{}, fmt.Errorf("`%v` field isn't defined in %v or embedded struct", stringutil.ToUpperCamelCase(column), t)
}
fieldIndexes[i] = index
}
dest := make([]interface{}, len(columns))
var result []reflect.Value
for rows.Next() {
v := reflect.New(t).Elem()
for i, index := range fieldIndexes {
field := v.FieldByIndex(index)
dest[i] = field.Addr().Interface()
}
if err := rows.Scan(dest...); err != nil {
return reflect.Value{}, err
}
result = append(result, v)
}
if err := rows.Err(); err != nil {
return reflect.Value{}, err
}
for i := 0; i < ptrN; i++ {
t = reflect.PtrTo(t)
}
slice := reflect.MakeSlice(reflect.SliceOf(t), len(result), len(result))
for i, v := range result {
for j := 0; j < ptrN; j++ {
v = v.Addr()
}
slice.Index(i).Set(v)
}
return slice, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L666-L668
|
func (o *RepoOwners) Reviewers(path string) sets.String {
return o.entriesForFile(path, o.reviewers, false)
}
|
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmltree.go#L45-L105
|
func ParseXML(r io.Reader, op ...ParseSettings) (tree.Node, error) {
ov := ParseOptions{
Strict: true,
XMLRoot: xmlele.Root,
}
for _, i := range op {
i(&ov)
}
dec := xml.NewDecoder(r)
dec.CharsetReader = charset.NewReaderLabel
dec.Strict = ov.Strict
ordrPos := 1
xmlTree := ov.XMLRoot()
t, err := dec.Token()
if err != nil {
return nil, err
}
if head, ok := t.(xml.ProcInst); ok && head.Target == "xml" {
t, err = dec.Token()
}
opts := xmlbuilder.BuilderOpts{
Dec: dec,
}
for err == nil {
switch xt := t.(type) {
case xml.StartElement:
setEle(&opts, xmlTree, xt, &ordrPos)
xmlTree = xmlTree.CreateNode(&opts)
case xml.CharData:
setNode(&opts, xmlTree, xt, tree.NtChd, &ordrPos)
xmlTree = xmlTree.CreateNode(&opts)
case xml.Comment:
setNode(&opts, xmlTree, xt, tree.NtComm, &ordrPos)
xmlTree = xmlTree.CreateNode(&opts)
case xml.ProcInst:
setNode(&opts, xmlTree, xt, tree.NtPi, &ordrPos)
xmlTree = xmlTree.CreateNode(&opts)
case xml.EndElement:
xmlTree = xmlTree.EndElem()
case xml.Directive:
if dp, ok := xmlTree.(DirectiveParser); ok {
dp.Directive(xt.Copy(), dec)
}
}
t, err = dec.Token()
}
if err == io.EOF {
err = nil
}
return xmlTree, err
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L583-L588
|
func (c *closeOnce) safeClose() error {
c.writers.Lock()
err := c.Close()
c.writers.Unlock()
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L359-L520
|
func (r *ProtocolLXD) CopyStoragePoolVolume(pool string, source ContainerServer, sourcePool string, volume api.StorageVolume, args *StoragePoolVolumeCopyArgs) (RemoteOperation, error) {
if !r.HasExtension("storage_api_local_volume_handling") {
return nil, fmt.Errorf("The server is missing the required \"storage_api_local_volume_handling\" API extension")
}
if args != nil && args.VolumeOnly && !r.HasExtension("storage_api_volume_snapshots") {
return nil, fmt.Errorf("The target server is missing the required \"storage_api_volume_snapshots\" API extension")
}
req := api.StorageVolumesPost{
Name: args.Name,
Type: volume.Type,
Source: api.StorageVolumeSource{
Name: volume.Name,
Type: "copy",
Pool: sourcePool,
VolumeOnly: args.VolumeOnly,
},
}
req.Config = volume.Config
req.Description = volume.Description
if r == source {
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/storage-pools/%s/volumes/%s", url.QueryEscape(pool), url.QueryEscape(volume.Type)), req, "")
if err != nil {
return nil, err
}
rop := remoteOperation{
targetOp: op,
chDone: make(chan bool),
}
// Forward targetOp to remote op
go func() {
rop.err = rop.targetOp.Wait()
close(rop.chDone)
}()
return &rop, nil
}
if !r.HasExtension("storage_api_remote_volume_handling") {
return nil, fmt.Errorf("The server is missing the required \"storage_api_remote_volume_handling\" API extension")
}
sourceReq := api.StorageVolumePost{
Migration: true,
Name: volume.Name,
Pool: sourcePool,
VolumeOnly: args.VolumeOnly,
}
// Push mode migration
if args != nil && args.Mode == "push" {
// Get target server connection information
info, err := r.GetConnectionInfo()
if err != nil {
return nil, err
}
// Create the container
req.Source.Type = "migration"
req.Source.Mode = "push"
// Send the request
path := fmt.Sprintf("/storage-pools/%s/volumes/%s", url.QueryEscape(pool), url.QueryEscape(volume.Type))
// Send the request
op, _, err := r.queryOperation("POST", path, req, "")
if err != nil {
return nil, err
}
opAPI := op.Get()
targetSecrets := map[string]string{}
for k, v := range opAPI.Metadata {
targetSecrets[k] = v.(string)
}
// Prepare the source request
target := api.StorageVolumePostTarget{}
target.Operation = opAPI.ID
target.Websockets = targetSecrets
target.Certificate = info.Certificate
sourceReq.Target = &target
return r.tryMigrateStoragePoolVolume(source, sourcePool, sourceReq, info.Addresses)
}
// Get source server connection information
info, err := source.GetConnectionInfo()
if err != nil {
return nil, err
}
// Get secrets from source server
op, err := source.MigrateStoragePoolVolume(sourcePool, sourceReq)
if err != nil {
return nil, err
}
opAPI := op.Get()
// Prepare source server secrets for remote
sourceSecrets := map[string]string{}
for k, v := range opAPI.Metadata {
sourceSecrets[k] = v.(string)
}
// Relay mode migration
if args != nil && args.Mode == "relay" {
// Push copy source fields
req.Source.Type = "migration"
req.Source.Mode = "push"
// Send the request
path := fmt.Sprintf("/storage-pools/%s/volumes/%s", url.QueryEscape(pool), url.QueryEscape(volume.Type))
// Send the request
targetOp, _, err := r.queryOperation("POST", path, req, "")
if err != nil {
return nil, err
}
targetOpAPI := targetOp.Get()
// Extract the websockets
targetSecrets := map[string]string{}
for k, v := range targetOpAPI.Metadata {
targetSecrets[k] = v.(string)
}
// Launch the relay
err = r.proxyMigration(targetOp.(*operation), targetSecrets, source, op.(*operation), sourceSecrets)
if err != nil {
return nil, err
}
// Prepare a tracking operation
rop := remoteOperation{
targetOp: targetOp,
chDone: make(chan bool),
}
// Forward targetOp to remote op
go func() {
rop.err = rop.targetOp.Wait()
close(rop.chDone)
}()
return &rop, nil
}
// Pull mode migration
req.Source.Type = "migration"
req.Source.Mode = "pull"
req.Source.Operation = opAPI.ID
req.Source.Websockets = sourceSecrets
req.Source.Certificate = info.Certificate
return r.tryCreateStoragePoolVolume(pool, req, info.Addresses)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1060-L1062
|
func (p *SetDocumentContentParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetDocumentContent, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L991-L995
|
func (v *GetDOMCountersReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory10(&r, v)
return r.Error()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L27-L30
|
func Marshal(w io.Writer, v interface{}) (int, error) {
// delegate to xdr package's Marshal
return xdr.Marshal(w, v)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L609-L612
|
func (e LedgerEntryType) String() string {
name, _ := ledgerEntryTypeMap[int32(e)]
return name
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/group.go#L28-L44
|
func (dom *Domain) Groups() ([]*Group, error) {
var vl valueList
err := dom.cgp.request(listGroups{Domain: dom.Name}, &vl)
if err != nil {
return []*Group{}, err
}
vals := vl.compact()
grps := make([]*Group, len(vals))
for i, v := range vals {
g, err := dom.GetGroup(v)
if err != nil {
return grps, err
}
grps[i] = g
}
return grps, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L30-L35
|
func NewCommit(repoName string, commitID string) *pfs.Commit {
return &pfs.Commit{
Repo: NewRepo(repoName),
ID: commitID,
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/fix-update.go#L532-L546
|
func appendOrMergeKindMapping(mappedLoads []rule.LoadInfo, mappedKind config.MappedKind) []rule.LoadInfo {
// If mappedKind.KindLoad already exists in the list, create a merged copy.
for _, load := range mappedLoads {
if load.Name == mappedKind.KindLoad {
load.Symbols = append(load.Symbols, mappedKind.KindName)
return mappedLoads
}
}
// Add a new LoadInfo.
return append(mappedLoads, rule.LoadInfo{
Name: mappedKind.KindLoad,
Symbols: []string{mappedKind.KindName},
})
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/encode.go#L718-L723
|
func NewStreamEncoder(e Emitter) *StreamEncoder {
if e == nil {
panic("objconv.NewStreamEncoder: the emitter is nil")
}
return &StreamEncoder{Emitter: e}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/inspector/easyjson.go#L69-L73
|
func (v *EventTargetReloadedAfterCrash) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoInspector(&r, v)
return r.Error()
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/cobra.go#L16-L27
|
func RunFixedArgs(numArgs int, run func([]string) error) func(*cobra.Command, []string) {
return func(cmd *cobra.Command, args []string) {
if len(args) != numArgs {
fmt.Printf("expected %d arguments, got %d\n\n", numArgs, len(args))
cmd.Usage()
} else {
if err := run(args); err != nil {
ErrorAndExit("%v", err)
}
}
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/helpers.go#L57-L67
|
func LevelFromPermissions(permissions RepoPermissions) RepoPermissionLevel {
if permissions.Admin {
return Admin
} else if permissions.Push {
return Write
} else if permissions.Pull {
return Read
} else {
return None
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/merger/merger.go#L98-L160
|
func MergeFile(oldFile *rule.File, emptyRules, genRules []*rule.Rule, phase Phase, kinds map[string]rule.KindInfo) {
getMergeAttrs := func(r *rule.Rule) map[string]bool {
if phase == PreResolve {
return kinds[r.Kind()].MergeableAttrs
} else {
return kinds[r.Kind()].ResolveAttrs
}
}
// Merge empty rules into the file and delete any rules which become empty.
for _, emptyRule := range emptyRules {
if oldRule, _ := Match(oldFile.Rules, emptyRule, kinds[emptyRule.Kind()]); oldRule != nil {
if oldRule.ShouldKeep() {
continue
}
rule.MergeRules(emptyRule, oldRule, getMergeAttrs(emptyRule), oldFile.Path)
if oldRule.IsEmpty(kinds[oldRule.Kind()]) {
oldRule.Delete()
}
}
}
oldFile.Sync()
// Match generated rules with existing rules in the file. Keep track of
// rules with non-standard names.
matchRules := make([]*rule.Rule, len(genRules))
matchErrors := make([]error, len(genRules))
substitutions := make(map[string]string)
for i, genRule := range genRules {
oldRule, err := Match(oldFile.Rules, genRule, kinds[genRule.Kind()])
if err != nil {
// TODO(jayconrod): add a verbose mode and log errors. They are too chatty
// to print by default.
matchErrors[i] = err
continue
}
matchRules[i] = oldRule
if oldRule != nil {
if oldRule.Name() != genRule.Name() {
substitutions[genRule.Name()] = oldRule.Name()
}
}
}
// Rename labels in generated rules that refer to other generated rules.
if len(substitutions) > 0 {
for _, genRule := range genRules {
substituteRule(genRule, substitutions, kinds[genRule.Kind()])
}
}
// Merge generated rules with existing rules or append to the end of the file.
for i, genRule := range genRules {
if matchErrors[i] != nil {
continue
}
if matchRules[i] == nil {
genRule.Insert(oldFile)
} else {
rule.MergeRules(genRule, matchRules[i], getMergeAttrs(genRule), oldFile.Path)
}
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/artifacts.go#L29-L58
|
func (s *Spyglass) ListArtifacts(src string) ([]string, error) {
keyType, key, err := splitSrc(src)
if err != nil {
return []string{}, fmt.Errorf("error parsing src: %v", err)
}
gcsKey := ""
switch keyType {
case gcsKeyType:
gcsKey = key
case prowKeyType:
if gcsKey, err = s.prowToGCS(key); err != nil {
logrus.Warningf("Failed to get gcs source for prow job: %v", err)
}
default:
return nil, fmt.Errorf("Unrecognized key type for src: %v", src)
}
artifactNames, err := s.GCSArtifactFetcher.artifacts(gcsKey)
logFound := false
for _, name := range artifactNames {
if name == "build-log.txt" {
logFound = true
break
}
}
if err != nil || !logFound {
artifactNames = append(artifactNames, "build-log.txt")
}
return artifactNames, nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L826-L830
|
func (t *Iterator) fetchMore() {
if t.err == nil && len(t.listRes)+len(t.searchRes) == 0 && t.more != nil {
t.err = t.more(t)
}
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L1248-L1269
|
func (v *VM) PowerOff(options VMPowerOption) error {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
jobHandle = C.VixVM_PowerOff(v.handle,
C.VixVMPowerOpOptions(options), // powerOptions,
nil, // callbackProc,
nil) // clientData
defer C.Vix_ReleaseHandle(jobHandle)
err = C.vix_job_wait(jobHandle)
if C.VIX_OK != err {
return &Error{
Operation: "vm.PowerOff",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/router/migrate.go#L27-L103
|
func MigrateUniqueCollection() error {
conn, err := db.Conn()
if err != nil {
return err
}
defer conn.Close()
coll := conn.Collection("routers")
appColl := conn.Apps()
var appNames []string
err = appColl.Find(nil).Distinct("name", &appNames)
if err != nil {
return err
}
_, err = coll.RemoveAll(bson.M{"app": bson.M{"$nin": appNames}, "router": bson.M{"$nin": appNames}})
if err != nil {
return err
}
byAppMap, err := allDupEntries(coll)
if err != nil {
return err
}
var toRemove []bson.ObjectId
for appName, appEntries := range byAppMap {
toRemoveDups := checkAllDups(appEntries)
toRemove = append(toRemove, toRemoveDups...)
var toRemoveAddrs []bson.ObjectId
toRemoveAddrs, err = checkAppAddr(appColl, appName, appEntries)
if err != nil {
return err
}
toRemove = append(toRemove, toRemoveAddrs...)
}
_, err = coll.RemoveAll(bson.M{"_id": bson.M{"$in": toRemove}})
if err != nil {
return err
}
var routerAppNames []string
err = coll.Find(nil).Distinct("app", &routerAppNames)
if err != nil {
return err
}
var missingApps []string
err = appColl.Find(bson.M{"name": bson.M{"$nin": routerAppNames}}).Distinct("name", &missingApps)
if err != nil {
return err
}
for _, missingEntry := range missingApps {
err = coll.Insert(routerAppEntry{
App: missingEntry,
Router: missingEntry,
})
if err != nil {
return err
}
}
byAppMap, err = allDupEntries(coll)
if err != nil {
return err
}
if len(byAppMap) == 0 {
_, err = collection()
return err
}
errBuf := bytes.NewBuffer(nil)
fmt.Fprintln(errBuf, `ERROR: The following entries in 'db.routers' collection have inconsistent
duplicated entries that could not be fixed automatically. This could have
happened after running app-swap due to a bug in previous tsuru versions. You'll
have to manually check if the apps are swapped or not and remove the duplicated
entries accordingly:`)
for appName, entries := range byAppMap {
fmt.Fprintf(errBuf, "app %q:\n", appName)
for _, e := range entries {
fmt.Fprintf(errBuf, " %#v\n", e)
}
}
return errors.New(errBuf.String())
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1271-L1275
|
func (v *SetAdBlockingEnabledParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage14(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L69-L73
|
func (v *TerminateExecutionParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L275-L284
|
func (p *GetComputedStyleForNodeParams) Do(ctx context.Context) (computedStyle []*ComputedProperty, err error) {
// execute
var res GetComputedStyleForNodeReturns
err = cdp.Execute(ctx, CommandGetComputedStyleForNode, p, &res)
if err != nil {
return nil, err
}
return res.ComputedStyle, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1605-L1631
|
func (c *Client) AssignIssue(org, repo string, number int, logins []string) error {
c.log("AssignIssue", org, repo, number, logins)
assigned := make(map[string]bool)
var i Issue
_, err := c.request(&request{
method: http.MethodPost,
path: fmt.Sprintf("/repos/%s/%s/issues/%d/assignees", org, repo, number),
requestBody: map[string][]string{"assignees": logins},
exitCodes: []int{201},
}, &i)
if err != nil {
return err
}
for _, assignee := range i.Assignees {
assigned[NormLogin(assignee.Login)] = true
}
missing := MissingUsers{action: "assign"}
for _, login := range logins {
if !assigned[NormLogin(login)] {
missing.Users = append(missing.Users, login)
}
}
if len(missing.Users) > 0 {
return missing
}
return nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L381-L386
|
func (m *Mat) GetImage(channels int) *IplImage {
tmp := CreateImage(m.Cols(), m.Rows(), m.Type(), channels)
img := C.cvGetImage(unsafe.Pointer(m), (*C.IplImage)(tmp))
return (*IplImage)(img)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/client/client.go#L230-L252
|
func (c *Client) UpdateAll(state string) error {
c.lock.Lock()
defer c.lock.Unlock()
resources, err := c.storage.List()
if err != nil {
return err
}
if len(resources) == 0 {
return fmt.Errorf("no holding resource")
}
var allErrors error
for _, r := range resources {
if err := c.update(r.GetName(), state, nil); err != nil {
allErrors = multierror.Append(allErrors, err)
continue
}
if err := c.updateLocalResource(r, state, nil); err != nil {
allErrors = multierror.Append(allErrors, err)
}
}
return allErrors
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L118-L124
|
func (r *ReadBuffer) ReadUint32() uint32 {
if b := r.ReadBytes(4); b != nil {
return binary.BigEndian.Uint32(b)
}
return 0
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2073-L2077
|
func (v *InternalPropertyDescriptor) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime18(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_builder.go#L179-L182
|
func (cb *ContextBuilder) SetParentContext(ctx context.Context) *ContextBuilder {
cb.ParentContext = ctx
return cb
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/helpers.go#L135-L143
|
func Includes(all, subset []bson.ObjectId) bool {
for _, item := range subset {
if !Contains(all, item) {
return false
}
}
return true
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L804-L811
|
func (db *DB) hasPKTag(field *reflect.StructField) bool {
for _, tag := range db.tagsFromField(field) {
if tag == "pk" {
return true
}
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L2099-L2103
|
func (v *SetCookieParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork15(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/health.go#L49-L51
|
func (h *Health) ServeReady() {
h.healthMux.HandleFunc("/healthz/ready", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") })
}
|
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/pubsub.go#L31-L60
|
func (s *PubSubSubscription) Next() (*Message, error) {
if s.resp.Error != nil {
return nil, s.resp.Error
}
d := json.NewDecoder(s.resp.Output)
var r struct {
From []byte `json:"from,omitempty"`
Data []byte `json:"data,omitempty"`
Seqno []byte `json:"seqno,omitempty"`
TopicIDs []string `json:"topicIDs,omitempty"`
}
err := d.Decode(&r)
if err != nil {
return nil, err
}
from, err := peer.IDFromBytes(r.From)
if err != nil {
return nil, err
}
return &Message{
From: from,
Data: r.Data,
Seqno: r.Seqno,
TopicIDs: r.TopicIDs,
}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L722-L725
|
func (p PrintToPDFParams) WithMarginTop(marginTop float64) *PrintToPDFParams {
p.MarginTop = marginTop
return &p
}
|
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/server.go#L71-L79
|
func (s *Server) RemoveStream(id string) {
s.mu.Lock()
defer s.mu.Unlock()
if s.Streams[id] != nil {
s.Streams[id].close()
delete(s.Streams, id)
}
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/encode.go#L32-L43
|
func Marshal(v interface{}) (b []byte, err error) {
m := marshalerPool.Get().(*marshaler)
m.b.Truncate(0)
if err = (objconv.Encoder{Emitter: m}).Encode(v); err == nil {
b = make([]byte, m.b.Len())
copy(b, m.b.Bytes())
}
marshalerPool.Put(m)
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L671-L703
|
func (s *store) DeleteExpiredKeys(cutoff time.Time) {
s.worldLock.Lock()
defer s.worldLock.Unlock()
for {
node := s.ttlKeyHeap.top()
if node == nil || node.ExpireTime.After(cutoff) {
break
}
s.CurrentIndex++
e := newEvent(Expire, node.Path, s.CurrentIndex, node.CreatedIndex)
e.EtcdIndex = s.CurrentIndex
e.PrevNode = node.Repr(false, false, s.clock)
if node.IsDir() {
e.Node.Dir = true
}
callback := func(path string) { // notify function
// notify the watchers with deleted set true
s.WatcherHub.notifyWatchers(e, path, true)
}
s.ttlKeyHeap.pop()
node.Remove(true, true, callback)
reportExpiredKey()
s.Stats.Inc(ExpireCount)
s.WatcherHub.notify(e)
}
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1477-L1484
|
func (r *Raft) setState(state RaftState) {
r.setLeader("")
oldState := r.raftState.getState()
r.raftState.setState(state)
if oldState != state {
r.observe(state)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/compare.go#L135-L140
|
func mustInt64orLeaseID(val interface{}) int64 {
if v, ok := val.(LeaseID); ok {
return int64(v)
}
return mustInt64(val)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L952-L956
|
func (v *StartPreciseCoverageParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler11(&r, v)
return r.Error()
}
|
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L272-L376
|
func Open(dbpath string) {
max_ipv6_range.SetString("340282366920938463463374607431768211455", 10)
var err error
f, err = os.Open(dbpath)
if err != nil {
return
}
meta.databasetype = readuint8(1)
meta.databasecolumn = readuint8(2)
meta.databaseyear = readuint8(3)
meta.databasemonth = readuint8(4)
meta.databaseday = readuint8(5)
meta.ipv4databasecount = readuint32(6)
meta.ipv4databaseaddr = readuint32(10)
meta.ipv6databasecount = readuint32(14)
meta.ipv6databaseaddr = readuint32(18)
meta.ipv4indexbaseaddr = readuint32(22)
meta.ipv6indexbaseaddr = readuint32(26)
meta.ipv4columnsize = uint32(meta.databasecolumn << 2) // 4 bytes each column
meta.ipv6columnsize = uint32(16 + ((meta.databasecolumn - 1) << 2)) // 4 bytes each column, except IPFrom column which is 16 bytes
dbt := meta.databasetype
// since both IPv4 and IPv6 use 4 bytes for the below columns, can just do it once here
if country_position[dbt] != 0 {
country_position_offset = uint32(country_position[dbt] - 1) << 2
country_enabled = true
}
if region_position[dbt] != 0 {
region_position_offset = uint32(region_position[dbt] - 1) << 2
region_enabled = true
}
if city_position[dbt] != 0 {
city_position_offset = uint32(city_position[dbt] - 1) << 2
city_enabled = true
}
if isp_position[dbt] != 0 {
isp_position_offset = uint32(isp_position[dbt] - 1) << 2
isp_enabled = true
}
if domain_position[dbt] != 0 {
domain_position_offset = uint32(domain_position[dbt] - 1) << 2
domain_enabled = true
}
if zipcode_position[dbt] != 0 {
zipcode_position_offset = uint32(zipcode_position[dbt] - 1) << 2
zipcode_enabled = true
}
if latitude_position[dbt] != 0 {
latitude_position_offset = uint32(latitude_position[dbt] - 1) << 2
latitude_enabled = true
}
if longitude_position[dbt] != 0 {
longitude_position_offset = uint32(longitude_position[dbt] - 1) << 2
longitude_enabled = true
}
if timezone_position[dbt] != 0 {
timezone_position_offset = uint32(timezone_position[dbt] - 1) << 2
timezone_enabled = true
}
if netspeed_position[dbt] != 0 {
netspeed_position_offset = uint32(netspeed_position[dbt] - 1) << 2
netspeed_enabled = true
}
if iddcode_position[dbt] != 0 {
iddcode_position_offset = uint32(iddcode_position[dbt] - 1) << 2
iddcode_enabled = true
}
if areacode_position[dbt] != 0 {
areacode_position_offset = uint32(areacode_position[dbt] - 1) << 2
areacode_enabled = true
}
if weatherstationcode_position[dbt] != 0 {
weatherstationcode_position_offset = uint32(weatherstationcode_position[dbt] - 1) << 2
weatherstationcode_enabled = true
}
if weatherstationname_position[dbt] != 0 {
weatherstationname_position_offset = uint32(weatherstationname_position[dbt] - 1) << 2
weatherstationname_enabled = true
}
if mcc_position[dbt] != 0 {
mcc_position_offset = uint32(mcc_position[dbt] - 1) << 2
mcc_enabled = true
}
if mnc_position[dbt] != 0 {
mnc_position_offset = uint32(mnc_position[dbt] - 1) << 2
mnc_enabled = true
}
if mobilebrand_position[dbt] != 0 {
mobilebrand_position_offset = uint32(mobilebrand_position[dbt] - 1) << 2
mobilebrand_enabled = true
}
if elevation_position[dbt] != 0 {
elevation_position_offset = uint32(elevation_position[dbt] - 1) << 2
elevation_enabled = true
}
if usagetype_position[dbt] != 0 {
usagetype_position_offset = uint32(usagetype_position[dbt] - 1) << 2
usagetype_enabled = true
}
metaok = true
}
|
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L66-L71
|
func HTTPClient(h *http.Client) ClientParam {
return func(c *Client) error {
c.client = h
return nil
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/metrics.go#L44-L69
|
func GatherProwJobMetrics(pjs []prowapi.ProwJob) {
// map of job to job type to state to count
metricMap := make(map[string]map[string]map[string]float64)
for _, pj := range pjs {
if metricMap[pj.Spec.Job] == nil {
metricMap[pj.Spec.Job] = make(map[string]map[string]float64)
}
if metricMap[pj.Spec.Job][string(pj.Spec.Type)] == nil {
metricMap[pj.Spec.Job][string(pj.Spec.Type)] = make(map[string]float64)
}
metricMap[pj.Spec.Job][string(pj.Spec.Type)][string(pj.Status.State)]++
}
// This may be racing with the prometheus server but we need to remove
// stale metrics like triggered or pending jobs that are now complete.
prowJobs.Reset()
for job, jobMap := range metricMap {
for jobType, typeMap := range jobMap {
for state, count := range typeMap {
prowJobs.WithLabelValues(job, jobType, state).Set(count)
}
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4637-L4641
|
func (v *FontSizes) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage48(&r, v)
return r.Error()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.