_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L147-L152
|
func SameKey(src, dst []byte) bool {
if len(src) != len(dst) {
return false
}
return bytes.Equal(ParseKey(src), ParseKey(dst))
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/field.go#L16-L21
|
func (ts *TimeStamp) BeforeInsert() error {
n := now()
ts.CreatedAt = n
ts.UpdatedAt = n
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L55-L80
|
func backupCreate(s *state.State, args db.ContainerBackupArgs, sourceContainer container) error {
// Create the database entry
err := s.Cluster.ContainerBackupCreate(args)
if err != nil {
if err == db.ErrAlreadyDefined {
return fmt.Errorf("backup '%s' already exists", args.Name)
}
return errors.Wrap(err, "Insert backup info into database")
}
// Get the backup struct
b, err := backupLoadByName(s, sourceContainer.Project(), args.Name)
if err != nil {
return errors.Wrap(err, "Load backup object")
}
// Now create the empty snapshot
err = sourceContainer.Storage().ContainerBackupCreate(*b, sourceContainer)
if err != nil {
s.Cluster.ContainerBackupRemove(args.Name)
return errors.Wrap(err, "Backup storage")
}
return nil
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L225-L228
|
func (b *ChannelMemoryBackend) Log(level Level, calldepth int, rec *Record) error {
b.incoming <- rec
return nil
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/cddvd.go#L25-L70
|
func (v *VM) AttachCDDVD(drive *CDDVDDrive) error {
if running, _ := v.IsRunning(); running {
return &Error{
Operation: "vm.AttachCDDVD",
Code: 200000,
Text: "Virtual machine must be powered off in order to attach a CD/DVD drive.",
}
}
// Loads VMX file in memory
v.vmxfile.Read()
model := v.vmxfile.model
device := vmx.Device{}
if drive.Filename != "" {
device.Filename = drive.Filename
device.Type = vmx.CDROM_IMAGE
} else {
device.Type = vmx.CDROM_RAW
device.Autodetect = true
}
device.Present = true
device.StartConnected = true
if drive.Bus == "" {
drive.Bus = vmx.IDE
}
switch drive.Bus {
case vmx.IDE:
model.IDEDevices = append(model.IDEDevices, vmx.IDEDevice{Device: device})
case vmx.SCSI:
model.SCSIDevices = append(model.SCSIDevices, vmx.SCSIDevice{Device: device})
case vmx.SATA:
model.SATADevices = append(model.SATADevices, vmx.SATADevice{Device: device})
default:
return &Error{
Operation: "vm.AttachCDDVD",
Code: 200001,
Text: fmt.Sprintf("Unrecognized bus type: %s\n", drive.Bus),
}
}
return v.vmxfile.Write()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/revision.go#L49-L59
|
func newRevision(lg *zap.Logger, clock clockwork.Clock, retention int64, rg RevGetter, c Compactable) *Revision {
rc := &Revision{
lg: lg,
clock: clock,
retention: retention,
rg: rg,
c: c,
}
rc.ctx, rc.cancel = context.WithCancel(context.Background())
return rc
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/performance.go#L92-L101
|
func (p *GetMetricsParams) Do(ctx context.Context) (metrics []*Metric, err error) {
// execute
var res GetMetricsReturns
err = cdp.Execute(ctx, CommandGetMetrics, nil, &res)
if err != nil {
return nil, err
}
return res.Metrics, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_dest.go#L205-L207
|
func (d *dirImageDestination) PutManifest(ctx context.Context, manifest []byte) error {
return ioutil.WriteFile(d.ref.manifestPath(), manifest, 0644)
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L117-L134
|
func (s *etcdStore) Put(ctx context.Context, req *etcdserverpb.PutRequest) (*etcdserverpb.PutResponse, error) {
ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Put: req}
msgc, errc, err := s.proposeInternalRaftRequest(ireq)
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
s.cancelInternalRaftRequest(ireq)
return nil, ctx.Err()
case msg := <-msgc:
return msg.(*etcdserverpb.PutResponse), nil
case err := <-errc:
return nil, err
case <-s.quitc:
return nil, errStopped
}
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/internal/function/func.go#L71-L99
|
func NameOf(v reflect.Value) string {
fnc := runtime.FuncForPC(v.Pointer())
if fnc == nil {
return "<unknown>"
}
fullName := fnc.Name() // e.g., "long/path/name/mypkg.(*MyType).(long/path/name/mypkg.myMethod)-fm"
// Method closures have a "-fm" suffix.
fullName = strings.TrimSuffix(fullName, "-fm")
var name string
for len(fullName) > 0 {
inParen := strings.HasSuffix(fullName, ")")
fullName = strings.TrimSuffix(fullName, ")")
s := lastIdentRx.FindString(fullName)
if s == "" {
break
}
name = s + "." + name
fullName = strings.TrimSuffix(fullName, s)
if i := strings.LastIndexByte(fullName, '('); inParen && i >= 0 {
fullName = fullName[:i]
}
fullName = strings.TrimSuffix(fullName, ".")
}
return strings.TrimSuffix(name, ".")
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcawsprovisioner/tcawsprovisioner.go#L252-L256
|
func (awsProvisioner *AwsProvisioner) ListWorkerTypes() (*ListWorkerTypes, error) {
cd := tcclient.Client(*awsProvisioner)
responseObject, _, err := (&cd).APICall(nil, "GET", "/list-worker-types", new(ListWorkerTypes), nil)
return responseObject.(*ListWorkerTypes), err
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L139-L148
|
func (b *PointerRingBuf) Advance(n int) {
if n <= 0 {
return
}
if n > b.Readable {
n = b.Readable
}
b.Readable -= n
b.Beg = (b.Beg + n) % b.N
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/urls.go#L51-L60
|
func NewURLsValue(s string) *URLsValue {
if s == "" {
return &URLsValue{}
}
v := &URLsValue{}
if err := v.Set(s); err != nil {
plog.Panicf("new URLsValue should never fail: %v", err)
}
return v
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/blunderbuss/blunderbuss.go#L294-L300
|
func popRandom(set sets.String) string {
list := set.List()
sort.Strings(list)
sel := list[rand.Intn(len(list))]
set.Delete(sel)
return sel
}
|
https://github.com/haklop/gnotifier/blob/0de36badf60155d5953373ed432982b20c62fb91/gnotifier.go#L48-L52
|
func Notification(title, message string) GNotifier {
config := &Config{title, message, 5000, ""}
n := ¬ifier{Config: config}
return n
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/oci.go#L136-L168
|
func (m *manifestOCI1) UpdatedImage(ctx context.Context, options types.ManifestUpdateOptions) (types.Image, error) {
copy := manifestOCI1{ // NOTE: This is not a deep copy, it still shares slices etc.
src: m.src,
configBlob: m.configBlob,
m: manifest.OCI1Clone(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, but we really don't care.
switch options.ManifestMIMEType {
case "": // No conversion, OK
case manifest.DockerV2Schema1MediaType, manifest.DockerV2Schema1SignedMediaType:
// We can't directly convert to V1, but we can transitively convert via a V2 image
m2, err := copy.convertToManifestSchema2()
if err != nil {
return nil, err
}
return m2.UpdatedImage(ctx, types.ManifestUpdateOptions{
ManifestMIMEType: options.ManifestMIMEType,
InformationOnly: options.InformationOnly,
})
case manifest.DockerV2Schema2MediaType:
return copy.convertToManifestSchema2()
default:
return nil, errors.Errorf("Conversion of image manifest from %s to %s is not implemented", imgspecv1.MediaTypeImageManifest, options.ManifestMIMEType)
}
return memoryImageFromManifest(©), nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L182-L186
|
func (e *ExceptionDetails) Error() string {
// TODO: watch script parsed events and match the ExceptionDetails.ScriptID
// to the name/location of the actual code and display here
return fmt.Sprintf("encountered exception '%s' (%d:%d)", e.Text, e.LineNumber, e.ColumnNumber)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/downloader/downloader.go#L79-L108
|
func FindBaseProfile(ctx context.Context, client *storage.Client, bucket, prowJobName, artifactsDirName,
covProfileName string) ([]byte, error) {
dirOfJob := path.Join("logs", prowJobName)
strBuilds, err := listGcsObjects(ctx, client, bucket, dirOfJob+"/", "/")
if err != nil {
return nil, fmt.Errorf("error listing gcs objects: %v", err)
}
builds := sortBuilds(strBuilds)
profilePath := ""
for _, build := range builds {
buildDirPath := path.Join(dirOfJob, strconv.Itoa(build))
dirOfStatusJSON := path.Join(buildDirPath, statusJSON)
statusText, err := readGcsObject(ctx, client, bucket, dirOfStatusJSON)
if err != nil {
logrus.Infof("Cannot read finished.json (%s) in bucket '%s'", dirOfStatusJSON, bucket)
} else if isBuildSucceeded(statusText) {
artifactsDirPath := path.Join(buildDirPath, artifactsDirName)
profilePath = path.Join(artifactsDirPath, covProfileName)
break
}
}
if profilePath == "" {
return nil, fmt.Errorf("no healthy build found for job '%s' in bucket '%s'; total # builds = %v", dirOfJob, bucket, len(builds))
}
return readGcsObject(ctx, client, bucket, profilePath)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L425-L431
|
func (f *FakeClient) ListMilestones(org, repo string) ([]github.Milestone, error) {
milestones := []github.Milestone{}
for k, v := range f.MilestoneMap {
milestones = append(milestones, github.Milestone{Title: k, Number: v})
}
return milestones, nil
}
|
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L29-L34
|
func GetDefaultHTTPClient(timeout time.Duration) IHTTPClient {
client := http.Client{
Timeout: timeout,
}
return IHTTPClient(&client)
}
|
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L793-L819
|
func (v Value) Reader() io.ReadCloser {
x, ok := v.data.(stream)
if !ok {
return &errorReadCloser{fmt.Errorf("stream not present")}
}
var rd io.Reader
rd = io.NewSectionReader(v.r.f, x.offset, v.Key("Length").Int64())
if v.r.key != nil {
rd = decryptStream(v.r.key, v.r.useAES, x.ptr, rd)
}
filter := v.Key("Filter")
param := v.Key("DecodeParms")
switch filter.Kind() {
default:
panic(fmt.Errorf("unsupported filter %v", filter))
case Null:
// ok
case Name:
rd = applyFilter(rd, filter.Name(), param)
case Array:
for i := 0; i < filter.Len(); i++ {
rd = applyFilter(rd, filter.Index(i).Name(), param.Index(i))
}
}
return ioutil.NopCloser(rd)
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L324-L333
|
func (c APIClient) RestartDatum(jobID string, datumFilter []string) error {
_, err := c.PpsAPIClient.RestartDatum(
c.Ctx(),
&pps.RestartDatumRequest{
Job: NewJob(jobID),
DataFilters: datumFilter,
},
)
return grpcutil.ScrubGRPC(err)
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task.go#L25-L40
|
func (m *Task) UnmarshalJSON(raw []byte) error {
var aO0 NewTask
if err := swag.ReadJSON(raw, &aO0); err != nil {
return err
}
m.NewTask = aO0
var aO1 TaskAllOf1
if err := swag.ReadJSON(raw, &aO1); err != nil {
return err
}
m.TaskAllOf1 = aO1
return nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/html.go#L16-L19
|
func HTML(names ...string) Renderer {
e := New(Options{})
return e.HTML(names...)
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L834-L843
|
func (o *MapComplex64Option) Set(value string) error {
parts := stringMapRegex.Split(value, 2)
if len(parts) != 2 {
return fmt.Errorf("expected KEY=VALUE got '%s'", value)
}
val := Complex64Option{}
val.Set(parts[1])
(*o)[parts[0]] = val
return nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L57-L63
|
func (c APIClient) ExtractWriter(objects bool, w io.Writer) error {
writer := pbutil.NewWriter(w)
return c.Extract(objects, func(op *admin.Op) error {
_, err := writer.Write(op)
return err
})
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/fragmenting_writer.go#L152-L157
|
func (w *fragmentingWriter) ArgWriter(last bool) (ArgWriter, error) {
if err := w.BeginArgument(last); err != nil {
return nil, err
}
return w, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L124-L130
|
func (m *Member) CreateEtcdClient(opts ...grpc.DialOption) (*clientv3.Client, error) {
cfg, err := m.CreateEtcdClientConfig(opts...)
if err != nil {
return nil, err
}
return clientv3.New(*cfg)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L293-L312
|
func checkMain(ctxt *build.Context) (bool, []string, error) {
pkg, err := ctxt.ImportDir(*rootDir, 0)
if err != nil {
return false, nil, fmt.Errorf("unable to analyze source: %v", err)
}
if !pkg.IsCommand() {
errorf("Your app's package needs to be changed from %q to \"main\".\n", pkg.Name)
}
// Search for a "func main"
var hasMain bool
var appFiles []string
for _, f := range pkg.GoFiles {
n := filepath.Join(*rootDir, f)
appFiles = append(appFiles, n)
if hasMain, err = readFile(n); err != nil {
return false, nil, fmt.Errorf("error parsing %q: %v", n, err)
}
}
return hasMain, appFiles, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4136-L4140
|
func (v *GetDocumentParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom47(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/errors.go#L168-L174
|
func NewWrappedSystemError(code SystemErrCode, wrapped error) error {
if se, ok := wrapped.(SystemError); ok {
return se
}
return SystemError{code: code, msg: fmt.Sprint(wrapped), wrapped: wrapped}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/flakyjob-reporter.go#L69-L72
|
func (fjr *FlakyJobReporter) RegisterFlags() {
flag.StringVar(&fjr.flakyJobDataURL, "flakyjob-url", "https://storage.googleapis.com/k8s-metrics/flakes-latest.json", "The url where flaky job JSON data can be found.")
flag.IntVar(&fjr.syncCount, "flakyjob-count", 3, "The number of flaky jobs to try to sync to github.")
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L77-L88
|
func (m *Mapping) FilterFieldByName(name string) (*Field, error) {
field := m.FieldByName(name)
if field == nil {
return nil, fmt.Errorf("Unknown filter %q", name)
}
if field.Type.Code != TypeColumn {
return nil, fmt.Errorf("Unknown filter %q not a column", name)
}
return field, nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcnotify/tcnotify.go#L152-L156
|
func (notify *Notify) Irc(payload *PostIRCMessageRequest) error {
cd := tcclient.Client(*notify)
_, _, err := (&cd).APICall(payload, "POST", "/irc", nil, nil)
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plank/controller.go#L474-L494
|
func (c *Controller) startPod(pj prowapi.ProwJob) (string, string, error) {
buildID, err := c.getBuildID(pj.Spec.Job)
if err != nil {
return "", "", fmt.Errorf("error getting build ID: %v", err)
}
pod, err := decorate.ProwJobToPod(pj, buildID)
if err != nil {
return "", "", err
}
client, ok := c.pkcs[pj.ClusterAlias()]
if !ok {
return "", "", fmt.Errorf("unknown cluster alias %q", pj.ClusterAlias())
}
actual, err := client.CreatePod(*pod)
if err != nil {
return "", "", err
}
return buildID, actual.ObjectMeta.Name, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L227-L229
|
func (t *KeyType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L336-L339
|
func (p EmulateTouchFromMouseEventParams) WithDeltaY(deltaY float64) *EmulateTouchFromMouseEventParams {
p.DeltaY = deltaY
return &p
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L1030-L1047
|
func (m *member) Stop(t testing.TB) {
lg.Info(
"stopping a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-address", m.grpcAddr),
)
m.Close()
m.serverClosers = nil
lg.Info(
"stopped a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-address", m.grpcAddr),
)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/util.go#L65-L88
|
func longestConnected(tp rafthttp.Transporter, membs []types.ID) (types.ID, bool) {
var longest types.ID
var oldest time.Time
for _, id := range membs {
tm := tp.ActiveSince(id)
if tm.IsZero() { // inactive
continue
}
if oldest.IsZero() { // first longest candidate
oldest = tm
longest = id
}
if tm.Before(oldest) {
oldest = tm
longest = id
}
}
if uint64(longest) == 0 {
return longest, false
}
return longest, true
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1303-L1306
|
func (p SetFileInputFilesParams) WithBackendNodeID(backendNodeID cdp.BackendNodeID) *SetFileInputFilesParams {
p.BackendNodeID = backendNodeID
return &p
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/watch/watch.go#L41-L47
|
func (e *Event) Unmarshal(key *string, val proto.Message) error {
if err := CheckType(e.Template, val); err != nil {
return err
}
*key = string(e.Key)
return proto.Unmarshal(e.Value, val)
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/https_redirect.go#L85-L93
|
func HTTPToHTTPSRedirectHandler(w http.ResponseWriter, r *http.Request) {
url := r.URL
url.Scheme = "https"
if url.Host == "" {
url.Host = r.Host
}
w.Header().Set("Location", url.String())
w.WriteHeader(http.StatusMovedPermanently)
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L167-L186
|
func (a *Application) HashSecret() error {
// check length
if len(a.Secret) == 0 {
return nil
}
// generate hash from password
hash, err := bcrypt.GenerateFromPassword([]byte(a.Secret), bcrypt.DefaultCost)
if err != nil {
return err
}
// save hash
a.SecretHash = hash
// clear password
a.Secret = ""
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L68-L70
|
func OutgoingContextWithKey(ctx context.Context, key string) context.Context {
return outgoingContextWithMergedMetadata(ctx, "key", key)
}
|
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/role.go#L59-L62
|
func (role *Role) Get(name string) (Checker, bool) {
fc, ok := role.definitions[name]
return fc, ok
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/wal.go#L392-L499
|
func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
w.mu.Lock()
defer w.mu.Unlock()
rec := &walpb.Record{}
decoder := w.decoder
var match bool
for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
switch rec.Type {
case entryType:
e := mustUnmarshalEntry(rec.Data)
if e.Index > w.start.Index {
ents = append(ents[:e.Index-w.start.Index-1], e)
}
w.enti = e.Index
case stateType:
state = mustUnmarshalState(rec.Data)
case metadataType:
if metadata != nil && !bytes.Equal(metadata, rec.Data) {
state.Reset()
return nil, state, nil, ErrMetadataConflict
}
metadata = rec.Data
case crcType:
crc := decoder.crc.Sum32()
// current crc of decoder must match the crc of the record.
// do no need to match 0 crc, since the decoder is a new one at this case.
if crc != 0 && rec.Validate(crc) != nil {
state.Reset()
return nil, state, nil, ErrCRCMismatch
}
decoder.updateCRC(rec.Crc)
case snapshotType:
var snap walpb.Snapshot
pbutil.MustUnmarshal(&snap, rec.Data)
if snap.Index == w.start.Index {
if snap.Term != w.start.Term {
state.Reset()
return nil, state, nil, ErrSnapshotMismatch
}
match = true
}
default:
state.Reset()
return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
}
}
switch w.tail() {
case nil:
// We do not have to read out all entries in read mode.
// The last record maybe a partial written one, so
// ErrunexpectedEOF might be returned.
if err != io.EOF && err != io.ErrUnexpectedEOF {
state.Reset()
return nil, state, nil, err
}
default:
// We must read all of the entries if WAL is opened in write mode.
if err != io.EOF {
state.Reset()
return nil, state, nil, err
}
// decodeRecord() will return io.EOF if it detects a zero record,
// but this zero record may be followed by non-zero records from
// a torn write. Overwriting some of these non-zero records, but
// not all, will cause CRC errors on WAL open. Since the records
// were never fully synced to disk in the first place, it's safe
// to zero them out to avoid any CRC errors from new writes.
if _, err = w.tail().Seek(w.decoder.lastOffset(), io.SeekStart); err != nil {
return nil, state, nil, err
}
if err = fileutil.ZeroToEnd(w.tail().File); err != nil {
return nil, state, nil, err
}
}
err = nil
if !match {
err = ErrSnapshotNotFound
}
// close decoder, disable reading
if w.readClose != nil {
w.readClose()
w.readClose = nil
}
w.start = walpb.Snapshot{}
w.metadata = metadata
if w.tail() != nil {
// create encoder (chain crc with the decoder), enable appending
w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC())
if err != nil {
return
}
}
w.decoder = nil
return metadata, state, ents, err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L686-L689
|
func (c *Client) CreateOrgHook(org string, req HookRequest) (int, error) {
c.log("CreateOrgHook", org)
return c.createHook(org, nil, req)
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L1122-L1127
|
func (o *ListErrorOption) Set(value string) error {
val := ErrorOption{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L635-L692
|
func (c *Consumer) joinGroup() (*balancer, error) {
memberID, _ := c.membership()
req := &sarama.JoinGroupRequest{
GroupId: c.groupID,
MemberId: memberID,
SessionTimeout: int32(c.client.config.Group.Session.Timeout / time.Millisecond),
ProtocolType: "consumer",
}
meta := &sarama.ConsumerGroupMemberMetadata{
Version: 1,
Topics: append(c.coreTopics, c.extraTopics...),
UserData: c.client.config.Group.Member.UserData,
}
err := req.AddGroupProtocolMetadata(string(StrategyRange), meta)
if err != nil {
return nil, err
}
err = req.AddGroupProtocolMetadata(string(StrategyRoundRobin), meta)
if err != nil {
return nil, err
}
broker, err := c.client.Coordinator(c.groupID)
if err != nil {
c.closeCoordinator(broker, err)
return nil, err
}
resp, err := broker.JoinGroup(req)
if err != nil {
c.closeCoordinator(broker, err)
return nil, err
} else if resp.Err != sarama.ErrNoError {
c.closeCoordinator(broker, resp.Err)
return nil, resp.Err
}
var strategy *balancer
if resp.LeaderId == resp.MemberId {
members, err := resp.GetMembers()
if err != nil {
return nil, err
}
strategy, err = newBalancerFromMeta(c.client, Strategy(resp.GroupProtocol), members)
if err != nil {
return nil, err
}
}
c.membershipMu.Lock()
c.memberID = resp.MemberId
c.generationID = resp.GenerationId
c.membershipMu.Unlock()
return strategy, nil
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L201-L259
|
func (d *Destination) PutManifest(ctx context.Context, m []byte) error {
// We do not bother with types.ManifestTypeRejectedError; our .SupportedManifestMIMETypes() above is already providing only one alternative,
// so the caller trying a different manifest kind would be pointless.
var man manifest.Schema2
if err := json.Unmarshal(m, &man); err != nil {
return errors.Wrap(err, "Error parsing manifest")
}
if man.SchemaVersion != 2 || man.MediaType != manifest.DockerV2Schema2MediaType {
return errors.Errorf("Unsupported manifest type, need a Docker schema 2 manifest")
}
layerPaths, lastLayerID, err := d.writeLegacyLayerMetadata(man.LayersDescriptors)
if err != nil {
return err
}
if len(man.LayersDescriptors) > 0 {
if err := d.createRepositoriesFile(lastLayerID); err != nil {
return err
}
}
repoTags := []string{}
for _, tag := range d.repoTags {
// For github.com/docker/docker consumers, this works just as well as
// refString := ref.String()
// because when reading the RepoTags strings, github.com/docker/docker/reference
// normalizes both of them to the same value.
//
// Doing it this way to include the normalized-out `docker.io[/library]` does make
// a difference for github.com/projectatomic/docker consumers, with the
// “Add --add-registry and --block-registry options to docker daemon” patch.
// These consumers treat reference strings which include a hostname and reference
// strings without a hostname differently.
//
// Using the host name here is more explicit about the intent, and it has the same
// effect as (docker pull) in projectatomic/docker, which tags the result using
// a hostname-qualified reference.
// See https://github.com/containers/image/issues/72 for a more detailed
// analysis and explanation.
refString := fmt.Sprintf("%s:%s", tag.Name(), tag.Tag())
repoTags = append(repoTags, refString)
}
items := []ManifestItem{{
Config: man.ConfigDescriptor.Digest.Hex() + ".json",
RepoTags: repoTags,
Layers: layerPaths,
Parent: "",
LayerSources: nil,
}}
itemsBytes, err := json.Marshal(&items)
if err != nil {
return err
}
// FIXME? Do we also need to support the legacy format?
return d.sendBytes(manifestFileName, itemsBytes)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L523-L525
|
func (p *SetAsyncCallStackDepthParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandSetAsyncCallStackDepth, p, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1411-L1415
|
func (v SignedCertificateTimestamp) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork9(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L306-L323
|
func newPRSignedBy(keyType sbKeyType, keyPath string, keyData []byte, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) {
if !keyType.IsValid() {
return nil, InvalidPolicyFormatError(fmt.Sprintf("invalid keyType \"%s\"", keyType))
}
if len(keyPath) > 0 && len(keyData) > 0 {
return nil, InvalidPolicyFormatError("keyType and keyData cannot be used simultaneously")
}
if signedIdentity == nil {
return nil, InvalidPolicyFormatError("signedIdentity not specified")
}
return &prSignedBy{
prCommon: prCommon{Type: prTypeSignedBy},
KeyType: keyType,
KeyPath: keyPath,
KeyData: keyData,
SignedIdentity: signedIdentity,
}, nil
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L8755-L8762
|
func (r *RepositoryAsset) Locator(api *API) *RepositoryAssetLocator {
for _, l := range r.Links {
if l["rel"] == "self" {
return api.RepositoryAssetLocator(l["href"])
}
}
return nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L561-L568
|
func AndWithMask(src1, src2, dst, mask *IplImage) {
C.cvAnd(
unsafe.Pointer(src1),
unsafe.Pointer(src2),
unsafe.Pointer(dst),
unsafe.Pointer(mask),
)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L528-L531
|
func (p SetVirtualTimePolicyParams) WithWaitForNavigation(waitForNavigation bool) *SetVirtualTimePolicyParams {
p.WaitForNavigation = waitForNavigation
return &p
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/smtp_sender.go#L18-L41
|
func (sm SMTPSender) Send(message Message) error {
gm := gomail.NewMessage()
gm.SetHeader("From", message.From)
gm.SetHeader("To", message.To...)
gm.SetHeader("Subject", message.Subject)
gm.SetHeader("Cc", message.CC...)
gm.SetHeader("Bcc", message.Bcc...)
sm.addBodies(message, gm)
sm.addAttachments(message, gm)
for field, value := range message.Headers {
gm.SetHeader(field, value)
}
err := sm.Dialer.DialAndSend(gm)
if err != nil {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L362-L366
|
func (v *StartTrackingHeapObjectsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler4(&r, v)
return r.Error()
}
|
https://github.com/Jeffail/tunny/blob/4921fff29480bad359ad2fb3271fb461c8ffe1fc/tunny.go#L225-L251
|
func (p *Pool) SetSize(n int) {
p.workerMut.Lock()
defer p.workerMut.Unlock()
lWorkers := len(p.workers)
if lWorkers == n {
return
}
// Add extra workers if N > len(workers)
for i := lWorkers; i < n; i++ {
p.workers = append(p.workers, newWorkerWrapper(p.reqChan, p.ctor()))
}
// Asynchronously stop all workers > N
for i := n; i < lWorkers; i++ {
p.workers[i].stop()
}
// Synchronously wait for all workers > N to stop
for i := n; i < lWorkers; i++ {
p.workers[i].join()
}
// Remove stopped workers from slice
p.workers = p.workers[:n]
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/skus/m1small/m1small_builder.go#L6-L27
|
func (s *SkuM1SmallBuilder) New(tm skurepo.TaskManager, meta map[string]interface{}) skurepo.Sku {
var procurementMeta = make(map[string]interface{})
var userIdentifier string
if meta != nil {
if v, ok := meta[procurementMetaFieldName]; ok {
procurementMeta = v.(map[string]interface{})
}
if v, ok := meta[userIdentifierMetaFieldName]; ok {
userIdentifier = v.(string)
}
}
return &SkuM1Small{
Client: s.Client,
ProcurementMeta: procurementMeta,
TaskManager: tm,
UserIdentifier: userIdentifier,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L2151-L2155
|
func (v *Cookie) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoHar12(&r, v)
return r.Error()
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L407-L431
|
func rewriteUses(x *ast.Ident, f, fnot func(token.Pos) ast.Expr, scope []ast.Stmt) {
var lastF ast.Expr
ff := func(n interface{}) {
ptr, ok := n.(*ast.Expr)
if !ok {
return
}
nn := *ptr
// The child node was just walked and possibly replaced.
// If it was replaced and this is a negation, replace with fnot(p).
not, ok := nn.(*ast.UnaryExpr)
if ok && not.Op == token.NOT && not.X == lastF {
*ptr = fnot(nn.Pos())
return
}
if refersTo(nn, x) {
lastF = f(nn.Pos())
*ptr = lastF
}
}
for _, n := range scope {
walk(n, ff)
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L495-L499
|
func (v *TakePreciseCoverageReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler4(&r, v)
return r.Error()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6166-L6175
|
func (u PeerAddressIp) GetIpv6() (result [16]byte, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "Ipv6" {
result = *u.Ipv6
ok = true
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L1243-L1247
|
func (v *ShorthandEntry) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss10(&r, v)
return r.Error()
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/platform.go#L30-L41
|
func (p Platform) String() string {
switch {
case p.OS != "" && p.Arch != "":
return p.OS + "_" + p.Arch
case p.OS != "":
return p.OS
case p.Arch != "":
return p.Arch
default:
return ""
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/runner/watch_command.go#L41-L54
|
func NewWatchCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "watcher",
Short: "Performs watch operation",
Run: runWatcherFunc,
}
cmd.Flags().DurationVar(&runningTime, "running-time", 60, "number of seconds to run")
cmd.Flags().StringVar(&watchPrefix, "prefix", "", "the prefix to append on all keys")
cmd.Flags().IntVar(&noOfPrefixes, "total-prefixes", 10, "total no of prefixes to use")
cmd.Flags().IntVar(&watchPerPrefix, "watch-per-prefix", 10, "number of watchers per prefix")
cmd.Flags().IntVar(&totalKeys, "total-keys", 1000, "total number of keys to watch")
return cmd
}
|
https://github.com/oleiade/tempura/blob/1e4f5790d5066b19bd755d71402bb0b41f1e5ff9/tempura.go#L51-L66
|
func Create(dir, prefix string, data []byte) (path string, err error) {
var tmp *os.File
tmp, err = ioutil.TempFile(dir, prefix)
if err != nil {
return "", err
}
defer tmp.Close()
_, err = tmp.Write(data)
if err != nil {
return "", err
}
return tmp.Name(), nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L907-L978
|
func (r *ProtocolLXD) CreateContainerFile(containerName string, path string, args ContainerFileArgs) error {
if args.Type == "directory" {
if !r.HasExtension("directory_manipulation") {
return fmt.Errorf("The server is missing the required \"directory_manipulation\" API extension")
}
}
if args.Type == "symlink" {
if !r.HasExtension("file_symlinks") {
return fmt.Errorf("The server is missing the required \"file_symlinks\" API extension")
}
}
if args.WriteMode == "append" {
if !r.HasExtension("file_append") {
return fmt.Errorf("The server is missing the required \"file_append\" API extension")
}
}
// Prepare the HTTP request
requestURL := fmt.Sprintf("%s/1.0/containers/%s/files?path=%s", r.httpHost, url.QueryEscape(containerName), url.QueryEscape(path))
requestURL, err := r.setQueryAttributes(requestURL)
if err != nil {
return err
}
req, err := http.NewRequest("POST", requestURL, args.Content)
if err != nil {
return err
}
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Set the various headers
if args.UID > -1 {
req.Header.Set("X-LXD-uid", fmt.Sprintf("%d", args.UID))
}
if args.GID > -1 {
req.Header.Set("X-LXD-gid", fmt.Sprintf("%d", args.GID))
}
if args.Mode > -1 {
req.Header.Set("X-LXD-mode", fmt.Sprintf("%04o", args.Mode))
}
if args.Type != "" {
req.Header.Set("X-LXD-type", args.Type)
}
if args.WriteMode != "" {
req.Header.Set("X-LXD-write", args.WriteMode)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return err
}
// Check the return value for a cleaner error
_, _, err = lxdParseResponse(resp)
if err != nil {
return err
}
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L363-L375
|
func (pa *ConfigAgent) PushEventHandlers(owner, repo string) map[string]PushEventHandler {
pa.mut.Lock()
defer pa.mut.Unlock()
hs := map[string]PushEventHandler{}
for _, p := range pa.getPlugins(owner, repo) {
if h, ok := pushEventHandlers[p]; ok {
hs[p] = h
}
}
return hs
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/account_merge.go#L30-L47
|
func (b *AccountMergeBuilder) Mutate(muts ...interface{}) {
for _, m := range muts {
var err error
switch mut := m.(type) {
case AccountMergeMutator:
err = mut.MutateAccountMerge(b)
case OperationMutator:
err = mut.MutateOperation(&b.O)
default:
err = errors.New("Mutator type not allowed")
}
if err != nil {
b.Err = err
return
}
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L150-L158
|
func (f *PortForwarder) RunForDaemon(localPort, remotePort uint16) error {
if localPort == 0 {
localPort = pachdLocalPort
}
if remotePort == 0 {
remotePort = pachdRemotePort
}
return f.Run("pachd", localPort, remotePort)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L302-L304
|
func (t ButtonType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L659-L662
|
func (e AccountFlags) ValidEnum(v int32) bool {
_, ok := accountFlagsMap[v]
return ok
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L160-L162
|
func VerifyFormKV(key string, values ...string) http.HandlerFunc {
return VerifyForm(url.Values{key: values})
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L228-L250
|
func (n *NetworkTransport) CloseStreams() {
n.connPoolLock.Lock()
defer n.connPoolLock.Unlock()
// Close all the connections in the connection pool and then remove their
// entry.
for k, e := range n.connPool {
for _, conn := range e {
conn.Release()
}
delete(n.connPool, k)
}
// Cancel the existing connections and create a new context. Both these
// operations must always be done with the lock held otherwise we can create
// connection handlers that are holding a context that will never be
// cancelable.
n.streamCtxLock.Lock()
n.streamCancel()
n.setupStreamContext()
n.streamCtxLock.Unlock()
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/rule.go#L65-L74
|
func (r *Rule) AddUnmatch(unmatch string) error {
unmatchRegexp, err := regexp.Compile("(?i)" + unmatch)
if err != nil {
return err
}
r.Unmatch = append(r.Unmatch, unmatchRegexp)
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L254-L267
|
func IntersectSetsCase(one, other sets.String) sets.String {
lower := sets.NewString()
for item := range other {
lower.Insert(strings.ToLower(item))
}
intersection := sets.NewString()
for item := range one {
if lower.Has(strings.ToLower(item)) {
intersection.Insert(item)
}
}
return intersection
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/norwegian/step3.go#L11-L26
|
func step3(w *snowballword.SnowballWord) bool {
// Possible sufficies for this step, longest first.
suffix, suffixRunes := w.FirstSuffixIn(w.R1start, len(w.RS),
"hetslov", "eleg", "elig", "elov", "slov",
"leg", "eig", "lig", "els", "lov", "ig",
)
// If it is not in R1, do nothing
if suffix == "" || len(suffixRunes) > len(w.RS)-w.R1start {
return false
}
w.ReplaceSuffixRunes(suffixRunes, []rune(""), true)
return true
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1230-L1248
|
func (c APIClient) DiffFile(newRepoName, newCommitID, newPath, oldRepoName,
oldCommitID, oldPath string, shallow bool) ([]*pfs.FileInfo, []*pfs.FileInfo, error) {
var oldFile *pfs.File
if oldRepoName != "" {
oldFile = NewFile(oldRepoName, oldCommitID, oldPath)
}
resp, err := c.PfsAPIClient.DiffFile(
c.Ctx(),
&pfs.DiffFileRequest{
NewFile: NewFile(newRepoName, newCommitID, newPath),
OldFile: oldFile,
Shallow: shallow,
},
)
if err != nil {
return nil, nil, grpcutil.ScrubGRPC(err)
}
return resp.NewFiles, resp.OldFiles, nil
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L174-L203
|
func (c Client) JSONContext(ctx context.Context, method, path string, query url.Values, body io.Reader, response interface{}) (err error) {
resp, err := c.RequestContext(ctx, method, path, query, body, []string{"application/json"})
if err != nil {
return
}
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
if response != nil {
if resp.ContentLength == 0 {
return errors.New("empty response body")
}
contentType := resp.Header.Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
return fmt.Errorf("unsupported content type: %s", contentType)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = JSONUnmarshal(body, &response); err != nil {
return
}
}
return
}
|
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L200-L245
|
func (o Options) NewClient() (*Client, error) {
host := o.Host
c, err := connect(host, o.User, o.Password)
if err != nil {
return nil, err
}
if strings.LastIndex(o.Host, ":") > 0 {
host = host[:strings.LastIndex(o.Host, ":")]
}
client := new(Client)
if o.NoTLS {
client.conn = c
} else {
var tlsconn *tls.Conn
if o.TLSConfig != nil {
tlsconn = tls.Client(c, o.TLSConfig)
} else {
DefaultConfig.ServerName = host
newconfig := DefaultConfig
newconfig.ServerName = host
tlsconn = tls.Client(c, &newconfig)
}
if err = tlsconn.Handshake(); err != nil {
return nil, err
}
insecureSkipVerify := DefaultConfig.InsecureSkipVerify
if o.TLSConfig != nil {
insecureSkipVerify = o.TLSConfig.InsecureSkipVerify
}
if !insecureSkipVerify {
if err = tlsconn.VerifyHostname(host); err != nil {
return nil, err
}
}
client.conn = tlsconn
}
if err := client.init(&o); err != nil {
client.Close()
return nil, err
}
return client, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L421-L425
|
func (v *SamplingProfileNode) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory4(&r, v)
return r.Error()
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcindex/tcindex.go#L99-L103
|
func (index *Index) Ping() error {
cd := tcclient.Client(*index)
_, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil)
return err
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L200-L202
|
func (r *reqResReader) arg2Reader() (ArgReader, error) {
return r.argReader(false /* last */, reqResReaderPreArg2, reqResReaderPreArg3)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/imgproc.go#L122-L131
|
func ApproxPoly(src *Seq, header_size int, storage *MemStorage, method int, eps float64, recursive int) *Seq {
seq := C.cvApproxPoly(
unsafe.Pointer(src),
C.int(header_size),
(*C.CvMemStorage)(storage),
C.int(method),
C.double(eps),
C.int(recursive))
return (*Seq)(seq)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/response.go#L67-L75
|
func (r *Response) MetadataAsStringSlice() ([]string, error) {
sl := []string{}
err := r.MetadataAsStruct(&sl)
if err != nil {
return nil, err
}
return sl, nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/apply_src.go#L25-L27
|
func (a *applySource) reset() {
a.rnd = rand.New(rand.NewSource(a.seed))
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/merge.go#L98-L122
|
func mergeExprs(src, dst bzl.Expr) (bzl.Expr, error) {
if ShouldKeep(dst) {
return nil, nil
}
if src == nil && (dst == nil || isScalar(dst)) {
return nil, nil
}
if isScalar(src) {
return src, nil
}
srcExprs, err := extractPlatformStringsExprs(src)
if err != nil {
return nil, err
}
dstExprs, err := extractPlatformStringsExprs(dst)
if err != nil {
return nil, err
}
mergedExprs, err := mergePlatformStringsExprs(srcExprs, dstExprs)
if err != nil {
return nil, err
}
return makePlatformStringsExpr(mergedExprs), nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/oauth.go#L43-L52
|
func OAuthConsumerKey(c context.Context) (string, error) {
req := &pb.CheckOAuthSignatureRequest{}
res := &pb.CheckOAuthSignatureResponse{}
err := internal.Call(c, "user", "CheckOAuthSignature", req, res)
if err != nil {
return "", err
}
return *res.OauthConsumerKey, err
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L93-L96
|
func (l *PropertyList) Load(p []Property) error {
*l = append(*l, p...)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1162-L1165
|
func (p StartScreencastParams) WithEveryNthFrame(everyNthFrame int64) *StartScreencastParams {
p.EveryNthFrame = everyNthFrame
return &p
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L432-L482
|
func (db *DB) Delete(obj interface{}) (affected int64, err error) {
objs, rtype, tableName, err := db.tableObjs("Delete", obj)
if err != nil {
return -1, err
}
if len(objs) < 1 {
return 0, nil
}
for _, obj := range objs {
if hook, ok := obj.(BeforeDeleter); ok {
if err := hook.BeforeDelete(); err != nil {
return -1, err
}
}
}
pkIdx := db.findPKIndex(rtype, nil)
if len(pkIdx) < 1 {
return -1, fmt.Errorf(`Delete: fields of struct doesn't have primary key: "pk" struct tag must be specified for delete`)
}
var args []interface{}
for _, obj := range objs {
rv := reflect.Indirect(reflect.ValueOf(obj))
args = append(args, rv.FieldByIndex(pkIdx).Interface())
}
holders := make([]string, len(args))
for i := 0; i < len(holders); i++ {
holders[i] = db.dialect.PlaceHolder(i)
}
query := fmt.Sprintf("DELETE FROM %s WHERE %s IN (%s)",
db.dialect.Quote(tableName),
db.dialect.Quote(db.columnFromTag(rtype.FieldByIndex(pkIdx))),
strings.Join(holders, ", "))
stmt, err := db.prepare(query, args...)
if err != nil {
return -1, err
}
defer stmt.Close()
result, err := stmt.Exec(args...)
if err != nil {
return -1, err
}
affected, _ = result.RowsAffected()
for _, obj := range objs {
if hook, ok := obj.(AfterDeleter); ok {
if err := hook.AfterDelete(); err != nil {
return affected, err
}
}
}
return affected, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/conversion.go#L114-L130
|
func newLabels(issueID int, gLabels []github.Label, repository string) ([]sql.Label, error) {
labels := []sql.Label{}
repository = strings.ToLower(repository)
for _, label := range gLabels {
if label.Name == nil {
return nil, fmt.Errorf("Label is missing name field")
}
labels = append(labels, sql.Label{
IssueID: strconv.Itoa(issueID),
Name: *label.Name,
Repository: repository,
})
}
return labels, nil
}
|
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L134-L139
|
func (render *Render) RegisterFuncMap(name string, fc interface{}) {
if render.funcMaps == nil {
render.funcMaps = template.FuncMap{}
}
render.funcMaps[name] = fc
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L268-L271
|
func (p EnableParams) WithMaxResourceBufferSize(maxResourceBufferSize int64) *EnableParams {
p.MaxResourceBufferSize = maxResourceBufferSize
return &p
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/token-counter/token-counter.go#L125-L163
|
func (t TokenHandler) Process() {
lastRate, err := t.getCoreRate()
if err != nil {
glog.Fatalf("%s: Couldn't get rate limits: %v", t.login, err)
}
for {
halfPeriod := lastRate.Reset.Time.Sub(time.Now()) / 2
time.Sleep(halfPeriod)
newRate, err := t.getCoreRate()
if err != nil {
glog.Error("Failed to get CoreRate: ", err)
continue
}
// There is a bug in GitHub. They seem to reset the Remaining value before resetting the Reset value.
if !newRate.Reset.Time.Equal(lastRate.Reset.Time) || newRate.Remaining > lastRate.Remaining {
if err := t.influxdb.Push(
"github_token_count",
map[string]string{"login": t.login},
map[string]interface{}{"value": lastRate.Limit - lastRate.Remaining},
lastRate.Reset.Time,
); err != nil {
glog.Error("Failed to push count:", err)
}
// Make sure the timer is properly reset, and we have time anyway
time.Sleep(30 * time.Minute)
for {
newRate, err = t.getCoreRate()
if err == nil {
break
}
glog.Error("Failed to get CoreRate: ", err)
time.Sleep(time.Minute)
}
}
lastRate = newRate
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/experiment/tracer/trace.go#L71-L86
|
func (l linesByTimestamp) String() string {
sort.Sort(l)
var log string
for i, line := range l {
switch i {
case len(l) - 1:
log += string(line.actual)
default:
// buf.ReadBytes('\n') does not remove the newline
log += fmt.Sprintf("%s,\n", strings.TrimSuffix(string(line.actual), "\n"))
}
}
return fmt.Sprintf("[%s]", log)
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api.go#L288-L303
|
func DefaultTicket() string {
defaultTicketOnce.Do(func() {
if IsDevAppServer() {
defaultTicket = "testapp" + defaultTicketSuffix
return
}
appID := partitionlessAppID()
escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1)
majVersion := VersionID(nil)
if i := strings.Index(majVersion, "."); i > 0 {
majVersion = majVersion[:i]
}
defaultTicket = fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID())
})
return defaultTicket
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L616-L618
|
func Xor(src1, src2, dst *IplImage) {
XorWithMask(src1, src2, dst, nil)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.