_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L385-L387
|
func NewSTMReadCommitted(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(ReadCommitted))
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L649-L655
|
func (r *Rule) Attr(key string) bzl.Expr {
attr, ok := r.attrs[key]
if !ok {
return nil
}
return attr.RHS
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/taskmanager/agent.go#L21-L36
|
func (s *Agent) Run(process func(*Agent) error) {
s.task.Update(func(t *Task) interface{} {
t.taskManager = s.taskManager
t.Status = AgentTaskStatusRunning
return t
})
s.statusEmitter <- AgentTaskStatusRunning
go s.startTaskPoller()
go s.listenForPoll()
go func(agent Agent) {
s := &agent
s.processExitHanderlDecorate(process)
<-s.processComplete
}(*s)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L300-L302
|
func (p *StopTrackingHeapObjectsParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStopTrackingHeapObjects, p, nil)
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L650-L694
|
func (p *Pact) VerifyMessageConsumerRaw(message *Message, handler MessageConsumer) error {
log.Printf("[DEBUG] verify message")
p.Setup(false)
// Reify the message back to its "example/generated" form
reified, err := p.pactClient.ReifyMessage(&types.PactReificationRequest{
Message: message.Content,
})
if err != nil {
return fmt.Errorf("unable to convert consumer test to a valid JSON representation: %v", err)
}
t := reflect.TypeOf(message.Type)
if t != nil && t.Name() != "interface" {
log.Println("[DEBUG] narrowing type to", t.Name())
err = json.Unmarshal(reified.ResponseRaw, &message.Type)
if err != nil {
return fmt.Errorf("unable to narrow type to %v: %v", t.Name(), err)
}
}
// Yield message, and send through handler function
generatedMessage :=
Message{
Content: message.Type,
States: message.States,
Description: message.Description,
Metadata: message.Metadata,
}
err = handler(generatedMessage)
if err != nil {
return err
}
// If no errors, update Message Pact
return p.pactClient.UpdateMessagePact(types.PactMessageRequest{
Message: message,
Consumer: p.Consumer,
Provider: p.Provider,
PactDir: p.PactDir,
})
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/uuid.go#L73-L77
|
func (s *Xor64Source) next() uint64 {
x := xor64(uint64(*s))
*s = Xor64Source(x)
return x
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/levels.go#L369-L371
|
func (s *levelsController) isLevel0Compactable() bool {
return s.levels[0].numTables() >= s.kv.opt.NumLevelZeroTables
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/cobra.go#L193-L225
|
func CreateAlias(cmd *cobra.Command, invocation string) *cobra.Command {
// Create logical commands for each substring in each invocation
var root, prev *cobra.Command
args := strings.Split(invocation, " ")
for i, arg := range args {
cur := &cobra.Command{}
// The leaf command node should include the usage from the given cmd,
// while logical nodes just need one piece of the invocation.
if i == len(args)-1 {
*cur = *cmd
if cmd.Use == "" {
cur.Use = arg
} else {
cur.Use = strings.Replace(cmd.Use, "{{alias}}", arg, -1)
}
cur.Example = strings.Replace(cmd.Example, "{{alias}}", fmt.Sprintf("%s %s", os.Args[0], invocation), -1)
} else {
cur.Use = arg
}
if root == nil {
root = cur
} else if prev != nil {
prev.AddCommand(cur)
}
prev = cur
}
return root
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/ledger_key.go#L39-L48
|
func (key *LedgerKey) SetAccount(account AccountId) error {
data := LedgerKeyAccount{account}
nkey, err := NewLedgerKey(LedgerEntryTypeAccount, data)
if err != nil {
return err
}
*key = nkey
return nil
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L1067-L1076
|
func (o *MapErrorOption) Set(value string) error {
parts := stringMapRegex.Split(value, 2)
if len(parts) != 2 {
return fmt.Errorf("expected KEY=VALUE got '%s'", value)
}
val := ErrorOption{}
val.Set(parts[1])
(*o)[parts[0]] = val
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/local.go#L36-L48
|
func localSetAccess(path string, group string) error {
err := socketUnixSetPermissions(path, 0660)
if err != nil {
return err
}
err = socketUnixSetOwnership(path, group)
if err != nil {
return err
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L18-L36
|
func PrintServerInfo(c lxd.ContainerServer) error {
server, _, err := c.GetServer()
if err != nil {
return err
}
env := server.Environment
fmt.Printf("Test environment:\n")
fmt.Printf(" Server backend: %s\n", env.Server)
fmt.Printf(" Server version: %s\n", env.ServerVersion)
fmt.Printf(" Kernel: %s\n", env.Kernel)
fmt.Printf(" Kernel architecture: %s\n", env.KernelArchitecture)
fmt.Printf(" Kernel version: %s\n", env.KernelVersion)
fmt.Printf(" Storage backend: %s\n", env.Storage)
fmt.Printf(" Storage version: %s\n", env.StorageVersion)
fmt.Printf(" Container backend: %s\n", env.Driver)
fmt.Printf(" Container version: %s\n", env.DriverVersion)
fmt.Printf("\n")
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L106-L125
|
func StorageRootFromEnv() (string, error) {
storageRoot, ok := os.LookupEnv(PachRootEnvVar)
if !ok {
return "", fmt.Errorf("%s not found", PachRootEnvVar)
}
storageBackend, ok := os.LookupEnv(StorageBackendEnvVar)
if !ok {
return "", fmt.Errorf("%s not found", StorageBackendEnvVar)
}
// These storage backends do not like leading slashes
switch storageBackend {
case Amazon:
fallthrough
case Minio:
if len(storageRoot) > 0 && storageRoot[0] == '/' {
storageRoot = storageRoot[1:]
}
}
return storageRoot, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L280-L284
|
func (v SetPausedParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L142-L151
|
func Slice(s string, start, end int) string {
if end > -1 {
return s[start:end]
}
L := len(s)
if L+end > 0 {
return s[start : L-end]
}
return s[start:]
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/build.go#L91-L98
|
func CleanupBuildArtifacts() {
mu.Lock()
defer mu.Unlock()
if tmpDir != "" {
os.RemoveAll(tmpDir)
tmpDir = ""
}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L467-L473
|
func (p *Page) ReadAllLogs(logType string) ([]Log, error) {
if _, err := p.ReadNewLogs(logType); err != nil {
return nil, err
}
return append([]Log(nil), p.logs[logType]...), nil
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L267-L269
|
func (la *LogAdapter) Fatalm(m *Attrs, msg string, a ...interface{}) error {
return la.Log(LevelFatal, m, msg, a...)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/comments.go#L80-L87
|
func UpdateComments(issueID int, pullRequest bool, db *gorm.DB, client ClientInterface) {
latest := findLatestCommentUpdate(issueID, db, client.RepositoryName())
updateIssueComments(issueID, latest, db, client)
if pullRequest {
updatePullComments(issueID, latest, db, client)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/rm_command.go#L25-L41
|
func NewRemoveCommand() cli.Command {
return cli.Command{
Name: "rm",
Usage: "remove a key or a directory",
ArgsUsage: "<key>",
Flags: []cli.Flag{
cli.BoolFlag{Name: "dir", Usage: "removes the key if it is an empty directory or a key-value pair"},
cli.BoolFlag{Name: "recursive, r", Usage: "removes the key and all child keys(if it is a directory)"},
cli.StringFlag{Name: "with-value", Value: "", Usage: "previous value"},
cli.IntFlag{Name: "with-index", Value: 0, Usage: "previous index"},
},
Action: func(c *cli.Context) error {
rmCommandFunc(c, mustNewKeyAPI(c))
return nil
},
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L289-L306
|
func (r *RemoteCache) Head(remote, vcs string) (commit, tag string, err error) {
if vcs != "git" {
return "", "", fmt.Errorf("could not locate recent commit in repo %q with unknown version control scheme %q", remote, vcs)
}
v, err := r.head.ensure(remote, func() (interface{}, error) {
commit, err := r.HeadCmd(remote, vcs)
if err != nil {
return nil, err
}
return headValue{commit: commit}, nil
})
if err != nil {
return "", "", err
}
value := v.(headValue)
return value.commit, value.tag, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L240-L280
|
func fillDefaultResourceRequests(opts *AssetOpts, persistentDiskBackend backend) {
if persistentDiskBackend == localBackend {
// For local deployments, we set the resource requirements and cache sizes
// low so that pachyderm clusters will fit inside e.g. minikube or travis
if opts.BlockCacheSize == "" {
opts.BlockCacheSize = "256M"
}
if opts.PachdNonCacheMemRequest == "" {
opts.PachdNonCacheMemRequest = "256M"
}
if opts.PachdCPURequest == "" {
opts.PachdCPURequest = "0.25"
}
if opts.EtcdMemRequest == "" {
opts.EtcdMemRequest = "256M"
}
if opts.EtcdCPURequest == "" {
opts.EtcdCPURequest = "0.25"
}
} else {
// For non-local deployments, we set the resource requirements and cache
// sizes higher, so that the cluster is stable and performant
if opts.BlockCacheSize == "" {
opts.BlockCacheSize = "1G"
}
if opts.PachdNonCacheMemRequest == "" {
opts.PachdNonCacheMemRequest = "2G"
}
if opts.PachdCPURequest == "" {
opts.PachdCPURequest = "1"
}
if opts.EtcdMemRequest == "" {
opts.EtcdMemRequest = "2G"
}
if opts.EtcdCPURequest == "" {
opts.EtcdCPURequest = "1"
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L486-L490
|
func (v GetApplicationCacheForFrameReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoApplicationcache5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_dest.go#L132-L151
|
func tarDirectory(src, dst string) error {
// input is a stream of bytes from the archive of the directory at path
input, err := archive.Tar(src, archive.Uncompressed)
if err != nil {
return errors.Wrapf(err, "error retrieving stream of bytes from %q", src)
}
// creates the tar file
outFile, err := os.Create(dst)
if err != nil {
return errors.Wrapf(err, "error creating tar file %q", dst)
}
defer outFile.Close()
// copies the contents of the directory to the tar file
// TODO: This can take quite some time, and should ideally be cancellable using a context.Context.
_, err = io.Copy(outFile, input)
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/profiler.go#L229-L231
|
func (p *StopTypeProfileParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandStopTypeProfile, nil, nil)
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/paths.go#L214-L216
|
func umResourcesTypePath(restype string, resourceid string) string {
return um() + slash("resources") + slash(restype) + slash(resourceid)
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L134-L147
|
func makeBroadcastRouteStatusSlice(r *routes) []broadcastRouteStatus {
r.RLock()
defer r.RUnlock()
var slice []broadcastRouteStatus
for source, via := range r.broadcast {
var hops []string
for _, hop := range via {
hops = append(hops, hop.String())
}
slice = append(slice, broadcastRouteStatus{source.String(), hops})
}
return slice
}
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L144-L147
|
func (gi *GeoIP) GetOrg(ip string) string {
name, _ := gi.GetName(ip)
return name
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L192-L200
|
func (c APIClient) InspectJobOutputCommit(repoName, commitID string, blockState bool) (*pps.JobInfo, error) {
jobInfo, err := c.PpsAPIClient.InspectJob(
c.Ctx(),
&pps.InspectJobRequest{
OutputCommit: NewCommit(repoName, commitID),
BlockState: blockState,
})
return jobInfo, grpcutil.ScrubGRPC(err)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/mechanism_gpgme.go#L142-L166
|
func (m gpgmeSigningMechanism) Verify(unverifiedSignature []byte) (contents []byte, keyIdentity string, err error) {
signedBuffer := bytes.Buffer{}
signedData, err := gpgme.NewDataWriter(&signedBuffer)
if err != nil {
return nil, "", err
}
unverifiedSignatureData, err := gpgme.NewDataBytes(unverifiedSignature)
if err != nil {
return nil, "", err
}
_, sigs, err := m.ctx.Verify(unverifiedSignatureData, nil, signedData)
if err != nil {
return nil, "", err
}
if len(sigs) != 1 {
return nil, "", InvalidSignatureError{msg: fmt.Sprintf("Unexpected GPG signature count %d", len(sigs))}
}
sig := sigs[0]
// This is sig.Summary == gpgme.SigSumValid except for key trust, which we handle ourselves
if sig.Status != nil || sig.Validity == gpgme.ValidityNever || sig.ValidityReason != nil || sig.WrongKeyUsage {
// FIXME: Better error reporting eventually
return nil, "", InvalidSignatureError{msg: fmt.Sprintf("Invalid GPG signature: %#v", sig)}
}
return signedBuffer.Bytes(), sig.Fingerprint, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L991-L993
|
func (p *SetBypassCSPParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetBypassCSP, p, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/stmt.go#L15-L19
|
func RegisterStmt(sql string) int {
code := len(stmts)
stmts[code] = sql
return code
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3903-L3907
|
func (v *GetFileInfoReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom44(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tethering/easyjson.go#L164-L168
|
func (v *EventAccepted) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTethering1(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4865-L4869
|
func (v *GetCertificateParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork37(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L343-L346
|
func (p EmulateTouchFromMouseEventParams) WithModifiers(modifiers Modifier) *EmulateTouchFromMouseEventParams {
p.Modifiers = modifiers
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L688-L696
|
func (w *watchGrpcStream) broadcastResponse(wr *WatchResponse) bool {
for _, ws := range w.substreams {
select {
case ws.recvc <- wr:
case <-ws.donec:
}
}
return true
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/default.go#L181-L183
|
func Errm(m *Attrs, msg string, a ...interface{}) error {
return Errorm(m, msg, a...)
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/session_manager.go#L181-L183
|
func (sm *sessionManager) Describe(in chan<- *prometheus.Desc) {
sm.cleanupErrorsTotal.Describe(in)
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/docker_schema2.go#L156-L180
|
func (m *manifestSchema2) UpdatedImage(ctx context.Context, options types.ManifestUpdateOptions) (types.Image, error) {
copy := manifestSchema2{ // NOTE: This is not a deep copy, it still shares slices etc.
src: m.src,
configBlob: m.configBlob,
m: manifest.Schema2Clone(m.m),
}
if options.LayerInfos != nil {
if err := copy.m.UpdateLayerInfos(options.LayerInfos); err != nil {
return nil, err
}
}
// Ignore options.EmbeddedDockerReference: it may be set when converting from schema1 to schema2, but we really don't care.
switch options.ManifestMIMEType {
case "": // No conversion, OK
case manifest.DockerV2Schema1SignedMediaType, manifest.DockerV2Schema1MediaType:
return copy.convertToManifestSchema1(ctx, options.InformationOnly.Destination)
case imgspecv1.MediaTypeImageManifest:
return copy.convertToManifestOCI1(ctx)
default:
return nil, errors.Errorf("Conversion of image manifest from %s to %s is not implemented", manifest.DockerV2Schema2MediaType, options.ManifestMIMEType)
}
return memoryImageFromManifest(©), nil
}
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L153-L161
|
func Usaget(prefix string, spec interface{}, out io.Writer, tmpl *template.Template) error {
// gather first
infos, err := gatherInfo(prefix, spec)
if err != nil {
return err
}
return tmpl.Execute(out, infos)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L262-L266
|
func (v *ShapeOutsideInfo) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom1(&r, v)
return r.Error()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1904-L1912
|
func (u OperationBody) MustManageOfferOp() ManageOfferOp {
val, ok := u.GetManageOfferOp()
if !ok {
panic("arm ManageOfferOp is not set")
}
return val
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/level.go#L44-L51
|
func LogLevel(level string) (Level, error) {
for i, name := range levelNames {
if strings.EqualFold(name, level) {
return Level(i), nil
}
}
return ERROR, ErrInvalidLogLevel
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L152-L166
|
func (t *RecordMode) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch RecordMode(in.String()) {
case RecordModeRecordUntilFull:
*t = RecordModeRecordUntilFull
case RecordModeRecordContinuously:
*t = RecordModeRecordContinuously
case RecordModeRecordAsMuchAsPossible:
*t = RecordModeRecordAsMuchAsPossible
case RecordModeEchoToConsole:
*t = RecordModeEchoToConsole
default:
in.AddError(errors.New("unknown RecordMode value"))
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry.go#L87-L96
|
func isSafeRetryMutableRPC(err error) bool {
if ev, ok := status.FromError(err); ok && ev.Code() != codes.Unavailable {
// not safe for mutable RPCs
// e.g. interrupted by non-transient error that client cannot handle itself,
// or transient error while the connection has already been established
return false
}
desc := rpctypes.ErrorDesc(err)
return desc == "there is no address available" || desc == "there is no connection available"
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/codec.go#L72-L80
|
func (reg *Registry) Codecs() (codecs map[string]Codec) {
codecs = make(map[string]Codec)
reg.mutex.RLock()
for mimetype, codec := range reg.codecs {
codecs[mimetype] = codec
}
reg.mutex.RUnlock()
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher.go#L79-L87
|
func (w *watcher) Remove() {
w.hub.mutex.Lock()
defer w.hub.mutex.Unlock()
close(w.eventChan)
if w.remove != nil {
w.remove()
}
}
|
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/sexp/factory.go#L15-L18
|
func Parse(buf []byte, offset int) (interface{}, error) {
obj, _, err := parseReturningOffset(buf, offset)
return obj, err
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L302-L304
|
func (s *FakeTaskManager) FindAndStallTaskForCaller(callerName string) (t *taskmanager.Task, err error) {
return s.ReturnedTask, s.ReturnedErr
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/token-counter/token-counter.go#L55-L62
|
func GetGitHubClient(token string) *github.Client {
return github.NewClient(
oauth2.NewClient(
oauth2.NoContext,
oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),
),
)
}
|
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/view/preload.go#L16-L27
|
func PreloadFile(filename string, contentType string) (preloadFile, error) {
body, err := ioutil.ReadFile(filename)
if err != nil {
return preloadFile{}, err
}
if contentType == "" {
contentType = mime.TypeByExtension(path.Ext(filename))
}
header := make(http.Header)
header.Set("Content-Type", contentType)
return preloadFile{body, header}, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/tarball/tarball_src.go#L266-L268
|
func (*tarballImageSource) LayerInfosForCopy(ctx context.Context) ([]types.BlobInfo, error) {
return nil, nil
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L594-L596
|
func HTTPLoggerFunc(name string, hf http.HandlerFunc) http.Handler {
return glg.HTTPLoggerFunc(name, hf)
}
|
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/stagePlanner.go#L371-L445
|
func planValue(stream *tokenStream) (*evaluationStage, error) {
var token ExpressionToken
var symbol OperatorSymbol
var ret *evaluationStage
var operator evaluationOperator
var err error
if !stream.hasNext() {
return nil, nil
}
token = stream.next()
switch token.Kind {
case CLAUSE:
ret, err = planTokens(stream)
if err != nil {
return nil, err
}
// advance past the CLAUSE_CLOSE token. We know that it's a CLAUSE_CLOSE, because at parse-time we check for unbalanced parens.
stream.next()
// the stage we got represents all of the logic contained within the parens
// but for technical reasons, we need to wrap this stage in a "noop" stage which breaks long chains of precedence.
// see github #33.
ret = &evaluationStage{
rightStage: ret,
operator: noopStageRight,
symbol: NOOP,
}
return ret, nil
case CLAUSE_CLOSE:
// when functions have empty params, this will be hit. In this case, we don't have any evaluation stage to do,
// so we just return nil so that the stage planner continues on its way.
stream.rewind()
return nil, nil
case VARIABLE:
operator = makeParameterStage(token.Value.(string))
case NUMERIC:
fallthrough
case STRING:
fallthrough
case PATTERN:
fallthrough
case BOOLEAN:
symbol = LITERAL
operator = makeLiteralStage(token.Value)
case TIME:
symbol = LITERAL
operator = makeLiteralStage(float64(token.Value.(time.Time).Unix()))
case PREFIX:
stream.rewind()
return planPrefix(stream)
}
if operator == nil {
errorMsg := fmt.Sprintf("Unable to plan token kind: '%s', value: '%v'", token.Kind.String(), token.Value)
return nil, errors.New(errorMsg)
}
return &evaluationStage{
symbol: symbol,
operator: operator,
}, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/log/log.go#L88-L97
|
func (l *logger) Log(request interface{}, response interface{}, err error, duration time.Duration) {
if err != nil {
l.LogAtLevelFromDepth(request, response, err, duration, logrus.ErrorLevel, 4)
} else {
l.LogAtLevelFromDepth(request, response, err, duration, logrus.InfoLevel, 4)
}
// We have to grab the method's name here before we
// enter the goro's stack
go l.ReportMetric(getMethodName(), duration, err)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L259-L271
|
func (t *ShadowRootType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ShadowRootType(in.String()) {
case ShadowRootTypeUserAgent:
*t = ShadowRootTypeUserAgent
case ShadowRootTypeOpen:
*t = ShadowRootTypeOpen
case ShadowRootTypeClosed:
*t = ShadowRootTypeClosed
default:
in.AddError(errors.New("unknown ShadowRootType value"))
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L170-L179
|
func CachePath(path ...string) string {
varDir := os.Getenv("LXD_DIR")
logDir := "/var/cache/lxd"
if varDir != "" {
logDir = filepath.Join(varDir, "cache")
}
items := []string{logDir}
items = append(items, path...)
return filepath.Join(items...)
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L10469-L10527
|
func (loc *SchedulerLocator) ScheduleRecipe(options rsapi.APIParams) error {
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{}
var argumentsOpt = options["arguments"]
if argumentsOpt != nil {
p["arguments"] = argumentsOpt
}
var auditIdOpt = options["audit_id"]
if auditIdOpt != nil {
p["audit_id"] = auditIdOpt
}
var auditPeriodOpt = options["audit_period"]
if auditPeriodOpt != nil {
p["audit_period"] = auditPeriodOpt
}
var formalValuesOpt = options["formal_values"]
if formalValuesOpt != nil {
p["formal_values"] = formalValuesOpt
}
var policyOpt = options["policy"]
if policyOpt != nil {
p["policy"] = policyOpt
}
var recipeOpt = options["recipe"]
if recipeOpt != nil {
p["recipe"] = recipeOpt
}
var recipeIdOpt = options["recipe_id"]
if recipeIdOpt != nil {
p["recipe_id"] = recipeIdOpt
}
var threadOpt = options["thread"]
if threadOpt != nil {
p["thread"] = threadOpt
}
uri, err := loc.ActionPath("Scheduler", "schedule_recipe")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return 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 fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L507-L510
|
func (p GetPropertiesParams) WithAccessorPropertiesOnly(accessorPropertiesOnly bool) *GetPropertiesParams {
p.AccessorPropertiesOnly = accessorPropertiesOnly
return &p
}
|
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/sessionauth/login.go#L101-L104
|
func UpdateUser(s sessions.Session, user User) error {
s.Set(SessionKey, user.UniqueId())
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/leader.go#L93-L101
|
func (l *leader) gotLeader() {
l.mu.Lock()
defer l.mu.Unlock()
select {
case <-l.leaderc:
l.leaderc = make(chan struct{})
default:
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L78-L84
|
func socketUnixSetPermissions(path string, mode os.FileMode) error {
err := os.Chmod(path, mode)
if err != nil {
return fmt.Errorf("cannot set permissions on local socket: %v", err)
}
return nil
}
|
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/base64.go#L43-L64
|
func (bc *Base64Cleaner) Read(p []byte) (n int, err error) {
// Size our buf to smallest of len(p) or len(bc.buffer).
size := len(bc.buffer)
if size > len(p) {
size = len(p)
}
buf := bc.buffer[:size]
bn, err := bc.r.Read(buf)
for i := 0; i < bn; i++ {
switch base64CleanerTable[buf[i]&0x7f] {
case -2:
// Strip these silently: tab, \n, \r, space, equals sign.
case -1:
// Strip these, but warn the client.
bc.Errors = append(bc.Errors, fmt.Errorf("Unexpected %q in Base64 stream", buf[i]))
default:
p[n] = buf[i]
n++
}
}
return
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L121-L135
|
func (ref dirReference) PolicyConfigurationNamespaces() []string {
res := []string{}
path := ref.resolvedPath
for {
lastSlash := strings.LastIndex(path, "/")
if lastSlash == -1 || lastSlash == 0 {
break
}
path = path[:lastSlash]
res = append(res, path)
}
// Note that we do not include "/"; it is redundant with the default "" global default,
// and rejected by dirTransport.ValidatePolicyConfigurationScope above.
return res
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L62-L80
|
func (f *Filtered) WithFields(fields log.Fields) log.Interface {
res := make(map[string]interface{}, len(fields))
for k, v := range fields {
val := v
// apply the filters
for _, filter := range f.filters {
val = filter.Filter(k, val)
}
res[k] = val
}
return &Filtered{
Interface: f.Interface.WithFields(res),
filters: f.filters,
}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L590-L607
|
func (txn *Txn) Commit() error {
txn.commitPrecheck() // Precheck before discarding txn.
defer txn.Discard()
if len(txn.writes) == 0 {
return nil // Nothing to do.
}
txnCb, err := txn.commitAndSend()
if err != nil {
return err
}
// If batchSet failed, LSM would not have been updated. So, no need to rollback anything.
// TODO: What if some of the txns successfully make it to value log, but others fail.
// Nothing gets updated to LSM, until a restart happens.
return txnCb()
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L361-L413
|
func ParseRoute(moniker string, routes []string) (pathPatterns []*gen.PathPattern) {
// :(((( some routes are empty
var paths []string
var method string
switch moniker {
case "Deployments#servers":
method, paths = "GET", []string{"/api/deployments/:id/servers"}
case "ServerArrays#current_instances":
method, paths = "GET", []string{"/api/server_arrays/:id/current_instances"}
case "ServerArrays#launch":
method, paths = "POST", []string{"/api/server_arrays/:id/launch"}
case "ServerArrays#multi_run_executable":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_run_executable"}
case "ServerArrays#multi_terminate":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_terminate"}
case "Servers#launch":
method, paths = "POST", []string{"/api/servers/:id/launch"}
case "Servers#terminate":
method, paths = "POST", []string{"/api/servers/:id/terminate"}
default:
for _, route := range routes {
bound := routeRegexp.FindStringIndex(route)
match := route[0:bound[0]]
method = strings.TrimRight(match[0:7], " ")
path := strings.TrimRight(match[7:], " ")
path = strings.TrimSuffix(path, "(.:format)?")
if isDeprecated(path) || isCustom(method, path) {
continue
}
paths = append(paths, path)
}
}
pathPatterns = make([]*gen.PathPattern, len(paths))
for i, p := range paths {
rx := routeVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(p), `/([^/]+)`)
rx = fmt.Sprintf("^%s$", rx)
pattern := gen.PathPattern{
HTTPMethod: method,
Path: p,
Pattern: routeVariablesRegexp.ReplaceAllLiteralString(p, "/%s"),
Regexp: rx,
}
matches := routeVariablesRegexp.FindAllStringSubmatch(p, -1)
if len(matches) > 0 {
pattern.Variables = make([]string, len(matches))
for i, m := range matches {
pattern.Variables[i] = m[1]
}
}
pathPatterns[i] = &pattern
}
return
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L589-L639
|
func (db *DB) writeRequests(reqs []*request) error {
if len(reqs) == 0 {
return nil
}
done := func(err error) {
for _, r := range reqs {
r.Err = err
r.Wg.Done()
}
}
db.elog.Printf("writeRequests called. Writing to value log")
err := db.vlog.write(reqs)
if err != nil {
done(err)
return err
}
db.elog.Printf("Writing to memtable")
var count int
for _, b := range reqs {
if len(b.Entries) == 0 {
continue
}
count += len(b.Entries)
var i uint64
for err = db.ensureRoomForWrite(); err == errNoRoom; err = db.ensureRoomForWrite() {
i++
if i%100 == 0 {
db.elog.Printf("Making room for writes")
}
// We need to poll a bit because both hasRoomForWrite and the flusher need access to s.imm.
// When flushChan is full and you are blocked there, and the flusher is trying to update s.imm,
// you will get a deadlock.
time.Sleep(10 * time.Millisecond)
}
if err != nil {
done(err)
return errors.Wrap(err, "writeRequests")
}
if err := db.writeToLSM(b); err != nil {
done(err)
return errors.Wrap(err, "writeRequests")
}
db.updateHead(b.Ptrs)
}
done(nil)
db.elog.Printf("%d entries written", count)
return nil
}
|
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/assetfs/filesystem.go#L55-L62
|
func (fs *AssetFileSystem) Asset(name string) ([]byte, error) {
for _, pth := range fs.paths {
if _, err := os.Stat(filepath.Join(pth, name)); err == nil {
return ioutil.ReadFile(filepath.Join(pth, name))
}
}
return []byte{}, fmt.Errorf("%v not found", name)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L72-L74
|
func (t *GestureType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L664-L668
|
func (v *FrameWithManifest) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache7(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L658-L662
|
func (v *ReleaseSnapshotParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree6(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L247-L249
|
func (p *UnregisterParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandUnregister, p, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L19-L35
|
func (n *NodeTx) RaftNodes() ([]RaftNode, error) {
nodes := []RaftNode{}
dest := func(i int) []interface{} {
nodes = append(nodes, RaftNode{})
return []interface{}{&nodes[i].ID, &nodes[i].Address}
}
stmt, err := n.tx.Prepare("SELECT id, address FROM raft_nodes ORDER BY id")
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch raft nodes")
}
return nodes, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3771-L3775
|
func (v KeyframesRule) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss32(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L366-L370
|
func (auth *Auth) ExpandScopesGet(payload *SetOfScopes) (*SetOfScopes, error) {
cd := tcclient.Client(*auth)
responseObject, _, err := (&cd).APICall(payload, "GET", "/scopes/expand", new(SetOfScopes), nil)
return responseObject.(*SetOfScopes), err
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/gw/rpc.pb.gw.go#L1284-L1403
|
func RegisterClusterHandlerClient(ctx context.Context, mux *runtime.ServeMux, client etcdserverpb.ClusterClient) error {
mux.Handle("POST", pattern_Cluster_MemberAdd_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_Cluster_MemberAdd_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Cluster_MemberAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Cluster_MemberRemove_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_Cluster_MemberRemove_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Cluster_MemberRemove_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Cluster_MemberUpdate_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_Cluster_MemberUpdate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Cluster_MemberUpdate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Cluster_MemberList_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_Cluster_MemberList_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Cluster_MemberList_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
|
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L163-L168
|
func (m *Map) ZoomAll() error {
if C.mapnik_map_zoom_all(m.m) != 0 {
return m.lastError()
}
return nil
}
|
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/job.go#L377-L379
|
func (c *Client) DeleteJob(id string) error {
return c.delete([]string{"job", id})
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaces.go#L16-L46
|
func (n *ns) IsEnabled(namespace string) bool {
n.RLock()
defer n.RUnlock()
if namespace == "" {
return true
}
hasStar := false
included := false
for _, ns := range n.namespaces {
// if the namspace is negated, it can never be enabled
if ns == negate(namespace) {
return false
}
// if the namespace is explicitly enabled, mark it as included
if ns == namespace {
included = true
}
// mark that we have a *
if ns == "*" {
hasStar = true
}
}
// non-mentioned namespaces are only enabled if we got the catch-all *
return hasStar || included
}
|
https://github.com/Financial-Times/base-ft-rw-app-go/blob/1ea8a13e1f37b95318cd965796558d932750f407/baseftrwapp/http_handlers.go#L192-L194
|
func buildInfoHandler(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "build-info")
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssd/codegen_client.go#L88-L90
|
func (api *API) ScheduleLocator(href string) *ScheduleLocator {
return &ScheduleLocator{Href(href), api}
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L120-L128
|
func (item *Item) ValueCopy(dst []byte) ([]byte, error) {
item.wg.Wait()
if item.status == prefetched {
return y.SafeCopy(dst, item.val), item.err
}
buf, cb, err := item.yieldItemValue()
defer runCallback(cb)
return y.SafeCopy(dst, buf), err
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L956-L964
|
func (this *Font) PutText(image *IplImage, text string, pt1 Point, color Scalar) {
C.cvPutText(
unsafe.Pointer(image),
C.CString(text),
C.cvPoint(C.int(pt1.X), C.int(pt1.Y)),
&this.font,
(C.CvScalar)(color),
)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/requiresig/requiresig.go#L182-L189
|
func shouldPrune(log *logrus.Entry, botName string) func(github.IssueComment) bool {
return func(comment github.IssueComment) bool {
if comment.User.Login != botName {
return false
}
return strings.Contains(comment.Body, needsSIGMessage)
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3436-L3445
|
func NewAllowTrustResult(code AllowTrustResultCode, value interface{}) (result AllowTrustResult, err error) {
result.Code = code
switch AllowTrustResultCode(code) {
case AllowTrustResultCodeAllowTrustSuccess:
// void
default:
// void
}
return
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/domain.go#L49-L51
|
func (cgp *CGP) Domain(name string) *Domain {
return &Domain{cgp: cgp, Name: name}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3931-L3935
|
func (v *GetAppManifestReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage42(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/log/log.go#L90-L101
|
func (t *Target) Errorf(format string, v ...interface{}) {
t.mut.RLock()
defer t.mut.RUnlock()
if t.logger != nil {
t.logger.Errorf(format, v...)
for _, item := range v {
if _, hasStack := item.(withStack); hasStack {
t.logger.Errorf("stack for error: %+v", item)
}
}
}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/mail.go#L12-L19
|
func NewMessage() Message {
return Message{
Context: context.Background(),
Headers: map[string]string{},
Data: render.Data{},
moot: &sync.RWMutex{},
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L3076-L3080
|
func (v *CaptureSnapshotReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot14(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config_logging.go#L48-L274
|
func (cfg *Config) setupLogging() error {
// handle "DeprecatedLogOutput" in v3.4
// TODO: remove "DeprecatedLogOutput" in v3.5
len1 := len(cfg.DeprecatedLogOutput)
len2 := len(cfg.LogOutputs)
if len1 != len2 {
switch {
case len1 > len2: // deprecate "log-output" flag is used
fmt.Fprintln(os.Stderr, "'--log-output' flag has been deprecated! Please use '--log-outputs'!")
cfg.LogOutputs = cfg.DeprecatedLogOutput
case len1 < len2: // "--log-outputs" flag has been set with multiple writers
cfg.DeprecatedLogOutput = []string{}
}
} else {
if len1 > 1 {
return errors.New("both '--log-output' and '--log-outputs' are set; only set '--log-outputs'")
}
if len1 < 1 {
return errors.New("either '--log-output' or '--log-outputs' flag must be set")
}
if reflect.DeepEqual(cfg.DeprecatedLogOutput, cfg.LogOutputs) && cfg.DeprecatedLogOutput[0] != DefaultLogOutput {
return fmt.Errorf("'--log-output=%q' and '--log-outputs=%q' are incompatible; only set --log-outputs", cfg.DeprecatedLogOutput, cfg.LogOutputs)
}
if !reflect.DeepEqual(cfg.DeprecatedLogOutput, []string{DefaultLogOutput}) {
fmt.Fprintf(os.Stderr, "Deprecated '--log-output' flag is set to %q\n", cfg.DeprecatedLogOutput)
fmt.Fprintln(os.Stderr, "Please use '--log-outputs' flag")
}
}
switch cfg.Logger {
case "capnslog": // TODO: deprecate this in v3.5
cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
if cfg.Debug {
capnslog.SetGlobalLogLevel(capnslog.DEBUG)
grpc.EnableTracing = true
// enable info, warning, error
grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stderr, os.Stderr, os.Stderr))
} else {
capnslog.SetGlobalLogLevel(capnslog.INFO)
// only discard info
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, os.Stderr, os.Stderr))
}
// TODO: deprecate with "capnslog"
if cfg.LogPkgLevels != "" {
repoLog := capnslog.MustRepoLogger("go.etcd.io/etcd")
settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
if err != nil {
plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
return nil
}
repoLog.SetLogLevel(settings)
}
if len(cfg.LogOutputs) != 1 {
return fmt.Errorf("--logger=capnslog supports only 1 value in '--log-outputs', got %q", cfg.LogOutputs)
}
// capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
// where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
// specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
output := cfg.LogOutputs[0]
switch output {
case StdErrLogOutput:
capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
case StdOutLogOutput:
capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
case DefaultLogOutput:
default:
return fmt.Errorf("unknown log-output %q (only supports %q, %q, %q)", output, DefaultLogOutput, StdErrLogOutput, StdOutLogOutput)
}
case "zap":
if len(cfg.LogOutputs) == 0 {
cfg.LogOutputs = []string{DefaultLogOutput}
}
if len(cfg.LogOutputs) > 1 {
for _, v := range cfg.LogOutputs {
if v == DefaultLogOutput {
return fmt.Errorf("multi logoutput for %q is not supported yet", DefaultLogOutput)
}
}
}
outputPaths, errOutputPaths := make([]string, 0), make([]string, 0)
isJournal := false
for _, v := range cfg.LogOutputs {
switch v {
case DefaultLogOutput:
outputPaths = append(outputPaths, StdErrLogOutput)
errOutputPaths = append(errOutputPaths, StdErrLogOutput)
case JournalLogOutput:
isJournal = true
case StdErrLogOutput:
outputPaths = append(outputPaths, StdErrLogOutput)
errOutputPaths = append(errOutputPaths, StdErrLogOutput)
case StdOutLogOutput:
outputPaths = append(outputPaths, StdOutLogOutput)
errOutputPaths = append(errOutputPaths, StdOutLogOutput)
default:
outputPaths = append(outputPaths, v)
errOutputPaths = append(errOutputPaths, v)
}
}
if !isJournal {
copied := logutil.AddOutputPaths(logutil.DefaultZapLoggerConfig, outputPaths, errOutputPaths)
if cfg.Debug {
copied.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
grpc.EnableTracing = true
}
if cfg.ZapLoggerBuilder == nil {
cfg.ZapLoggerBuilder = func(c *Config) error {
var err error
c.logger, err = copied.Build()
if err != nil {
return err
}
c.loggerMu.Lock()
defer c.loggerMu.Unlock()
c.loggerConfig = &copied
c.loggerCore = nil
c.loggerWriteSyncer = nil
grpcLogOnce.Do(func() {
// debug true, enable info, warning, error
// debug false, only discard info
var gl grpclog.LoggerV2
gl, err = logutil.NewGRPCLoggerV2(copied)
if err == nil {
grpclog.SetLoggerV2(gl)
}
})
return nil
}
}
} else {
if len(cfg.LogOutputs) > 1 {
for _, v := range cfg.LogOutputs {
if v != DefaultLogOutput {
return fmt.Errorf("running with systemd/journal but other '--log-outputs' values (%q) are configured with 'default'; override 'default' value with something else", cfg.LogOutputs)
}
}
}
// use stderr as fallback
syncer, lerr := getJournalWriteSyncer()
if lerr != nil {
return lerr
}
lvl := zap.NewAtomicLevelAt(zap.InfoLevel)
if cfg.Debug {
lvl = zap.NewAtomicLevelAt(zap.DebugLevel)
grpc.EnableTracing = true
}
// WARN: do not change field names in encoder config
// journald logging writer assumes field names of "level" and "caller"
cr := zapcore.NewCore(
zapcore.NewJSONEncoder(logutil.DefaultZapLoggerConfig.EncoderConfig),
syncer,
lvl,
)
if cfg.ZapLoggerBuilder == nil {
cfg.ZapLoggerBuilder = func(c *Config) error {
c.logger = zap.New(cr, zap.AddCaller(), zap.ErrorOutput(syncer))
c.loggerMu.Lock()
defer c.loggerMu.Unlock()
c.loggerConfig = nil
c.loggerCore = cr
c.loggerWriteSyncer = syncer
grpcLogOnce.Do(func() {
grpclog.SetLoggerV2(logutil.NewGRPCLoggerV2FromZapCore(cr, syncer))
})
return nil
}
}
}
err := cfg.ZapLoggerBuilder(cfg)
if err != nil {
return err
}
logTLSHandshakeFailure := func(conn *tls.Conn, err error) {
state := conn.ConnectionState()
remoteAddr := conn.RemoteAddr().String()
serverName := state.ServerName
if len(state.PeerCertificates) > 0 {
cert := state.PeerCertificates[0]
ips := make([]string, 0, len(cert.IPAddresses))
for i := range cert.IPAddresses {
ips[i] = cert.IPAddresses[i].String()
}
cfg.logger.Warn(
"rejected connection",
zap.String("remote-addr", remoteAddr),
zap.String("server-name", serverName),
zap.Strings("ip-addresses", ips),
zap.Strings("dns-names", cert.DNSNames),
zap.Error(err),
)
} else {
cfg.logger.Warn(
"rejected connection",
zap.String("remote-addr", remoteAddr),
zap.String("server-name", serverName),
zap.Error(err),
)
}
}
cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
default:
return fmt.Errorf("unknown logger option %q", cfg.Logger)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L7676-L7680
|
func (v *DeleteCookiesParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork60(&r, v)
return r.Error()
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L367-L377
|
func (si *ServiceInstance) Status(requestID string) (string, error) {
s, err := Get(si.ServiceName)
if err != nil {
return "", err
}
endpoint, err := s.getClient("production")
if err != nil {
return "", err
}
return endpoint.Status(si, requestID)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1726-L1730
|
func (v SetDataSizeLimitsForTestParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork12(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L170-L193
|
func (s storageReference) PolicyConfigurationNamespaces() []string {
storeSpec := "[" + s.transport.store.GraphDriverName() + "@" + s.transport.store.GraphRoot() + "]"
driverlessStoreSpec := "[" + s.transport.store.GraphRoot() + "]"
namespaces := []string{}
if s.named != nil {
if s.id != "" {
// The reference without the ID is also a valid namespace.
namespaces = append(namespaces, storeSpec+s.named.String())
}
tagged, isTagged := s.named.(reference.Tagged)
_, isDigested := s.named.(reference.Digested)
if isTagged && isDigested { // s.named is "name:tag@digest"; add a "name:tag" parent namespace.
namespaces = append(namespaces, storeSpec+s.named.Name()+":"+tagged.Tag())
}
components := strings.Split(s.named.Name(), "/")
for len(components) > 0 {
namespaces = append(namespaces, storeSpec+strings.Join(components, "/"))
components = components[:len(components)-1]
}
}
namespaces = append(namespaces, storeSpec)
namespaces = append(namespaces, driverlessStoreSpec)
return namespaces
}
|
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L505-L508
|
func (g *Glg) RawString(data []byte) string {
str := *(*string)(unsafe.Pointer(&data))
return str[strings.Index(str, sep)+sepl : len(str)-rcl]
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/pivnetrelease.go#L32-L38
|
func (r *PivnetRelease) BoshReleaseOrEmpty(name string) *BoshRelease {
br := r.BoshRelease[name]
if br == nil {
br = emptyBoshRelease
}
return br
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L157-L170
|
func FilterValues(f interface{}, opt Option) Option {
v := reflect.ValueOf(f)
if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() {
panic(fmt.Sprintf("invalid values filter function: %T", f))
}
if opt := normalizeOption(opt); opt != nil {
vf := &valuesFilter{fnc: v, opt: opt}
if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
vf.typ = ti
}
return vf
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.