_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/buffalo/cmd/fix/runner.go#L20-L50
|
func Run() error {
fmt.Printf("! This updater will attempt to update your application to Buffalo version: %s\n", runtime.Version)
if !ask("Do you wish to continue?") {
fmt.Println("~~~ cancelling update ~~~")
return nil
}
r := &Runner{
App: meta.New("."),
Warnings: []string{},
}
defer func() {
if len(r.Warnings) == 0 {
return
}
fmt.Println("\n\n----------------------------")
fmt.Printf("!!! (%d) Warnings Were Found !!!\n\n", len(r.Warnings))
for _, w := range r.Warnings {
fmt.Printf("[WARNING]: %s\n", w)
}
}()
for _, c := range checks {
if err := c(r); err != nil {
return err
}
}
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_unix.go#L79-L86
|
func Restore(fd int, state *State) error {
ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(&state.Termios)))
if ret != 0 {
return err.(syscall.Errno)
}
return nil
}
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/putter.go#L302-L316
|
func (p *putter) abort() {
v := url.Values{}
v.Set("uploadId", p.UploadID)
s := p.url.String() + "?" + v.Encode()
resp, err := p.retryRequest("DELETE", s, nil, nil)
if err != nil {
logger.Printf("Error aborting multipart upload: %v\n", err)
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 204 {
logger.Printf("Error aborting multipart upload: %v", newRespError(resp))
}
return
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L108-L125
|
func (ms *MemoryStorage) Entries(lo, hi, maxSize uint64) ([]pb.Entry, error) {
ms.Lock()
defer ms.Unlock()
offset := ms.ents[0].Index
if lo <= offset {
return nil, ErrCompacted
}
if hi > ms.lastIndex()+1 {
raftLogger.Panicf("entries' hi(%d) is out of bound lastindex(%d)", hi, ms.lastIndex())
}
// only contains dummy entries.
if len(ms.ents) == 1 {
return nil, ErrUnavailable
}
ents := ms.ents[lo-offset : hi-offset]
return limitSize(ents, maxSize), nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L31-L45
|
func NewRoleCommand() *cobra.Command {
ac := &cobra.Command{
Use: "role <subcommand>",
Short: "Role related commands",
}
ac.AddCommand(newRoleAddCommand())
ac.AddCommand(newRoleDeleteCommand())
ac.AddCommand(newRoleGetCommand())
ac.AddCommand(newRoleListCommand())
ac.AddCommand(newRoleGrantPermissionCommand())
ac.AddCommand(newRoleRevokePermissionCommand())
return ac
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/benchmark/internal_server.go#L86-L93
|
func (s *internalServer) Advertise(hyperbahnHosts []string) error {
config := hyperbahn.Configuration{InitialNodes: hyperbahnHosts}
hc, err := hyperbahn.NewClient(s.ch, config, nil)
if err != nil {
panic("failed to setup Hyperbahn client: " + err.Error())
}
return hc.Advertise()
}
|
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L79-L99
|
func (x *Exception) Run(s *Secret) bool {
match := true
if match && x.Rule != nil && !x.Rule.MatchString(s.Rule.Name) {
match = false
}
if match && x.Object != nil && !x.Object.MatchString(s.Object.Name) {
match = false
}
if match && x.Nline != nil && *x.Nline != s.Nline {
match = false
}
if match && x.Content != nil && !x.Content.MatchString(s.Line) {
match = false
}
return match
}
|
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L40-L51
|
func RegisterDatasources(path string) error {
cs := C.CString(path)
defer C.free(unsafe.Pointer(cs))
if C.mapnik_register_datasources(cs) == 0 {
e := C.GoString(C.mapnik_register_last_error())
if e != "" {
return errors.New("registering datasources: " + e)
}
return errors.New("error while registering datasources")
}
return nil
}
|
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L79-L81
|
func (now *Now) EndOfWeek() time.Time {
return now.BeginningOfWeek().AddDate(0, 0, 7).Add(-time.Nanosecond)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tethering/tethering.go#L35-L37
|
func (p *BindParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandBind, p, nil)
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqinfo/seqinfo.go#L155-L185
|
func printPlainResults(results Results) error {
for _, res := range results {
// Explicitely start with the string and error output
fmt.Printf("Source = %s\n", res.origString)
fmt.Printf(" String = %s\n", res.String)
if res.Error != "" {
fmt.Printf(" Error = %s\n", res.Error)
continue
}
// Dynamically loop over the rest of the fields
typ := reflect.TypeOf(*res)
val := reflect.ValueOf(*res)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.Name == "Error" || field.Name == "String" {
continue
}
if field.PkgPath != "" {
// ignore unexported fields
continue
}
fmt.Printf(" %s = %v\n", field.Name, val.Field(i).Interface())
}
fmt.Print("\n")
}
return nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L231-L241
|
func (k *Key) Encode() string {
ref := keyToProto("", k)
b, err := proto.Marshal(ref)
if err != nil {
panic(err)
}
// Trailing padding is stripped.
return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/build/controller.go#L519-L542
|
func prowJobStatus(bs buildv1alpha1.BuildStatus) (prowjobv1.ProwJobState, string) {
started := bs.StartTime
finished := bs.CompletionTime
pcond := bs.GetCondition(buildv1alpha1.BuildSucceeded)
if pcond == nil {
if !finished.IsZero() {
return prowjobv1.ErrorState, descMissingCondition
}
return prowjobv1.TriggeredState, descScheduling
}
cond := *pcond
switch {
case cond.Status == coreapi.ConditionTrue:
return prowjobv1.SuccessState, description(cond, descSucceeded)
case cond.Status == coreapi.ConditionFalse:
return prowjobv1.FailureState, description(cond, descFailed)
case started.IsZero():
return prowjobv1.TriggeredState, description(cond, descInitializing)
case cond.Status == coreapi.ConditionUnknown, finished.IsZero():
return prowjobv1.PendingState, description(cond, descRunning)
}
logrus.Warnf("Unknown condition %#v", cond)
return prowjobv1.ErrorState, description(cond, descUnknown) // shouldn't happen
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L215-L226
|
func (c *Controller) DefinedContainer(name string) (bool, error) {
devs, err := c.machine.Devices(gomaasapi.DevicesArgs{Hostname: []string{name}})
if err != nil {
return false, err
}
if len(devs) == 1 {
return true, nil
}
return false, nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L100-L106
|
func New(cfg Config) (*Client, error) {
if len(cfg.Endpoints) == 0 {
return nil, ErrNoAvailableEndpoints
}
return newClient(&cfg)
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/histogram.go#L80-L86
|
func createHistogramBins(minExponent, maxExponent uint32) []int64 {
var bins []int64
for i := minExponent; i <= maxExponent; i++ {
bins = append(bins, int64(1)<<i)
}
return bins
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/types.go#L44-L46
|
func (t CachedResponseType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3977-L3985
|
func (u OperationResultTr) MustCreateAccountResult() CreateAccountResult {
val, ok := u.GetCreateAccountResult()
if !ok {
panic("arm CreateAccountResult is not set")
}
return val
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L125-L127
|
func (s *FakeVCDClient) UnDeployVApp(vappID string) (task *vcloudclient.TaskElem, err error) {
return &s.FakeVApp.Tasks.Task, s.ErrDeployFake
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5735-L5739
|
func (v EventWebSocketCreated) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork45(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L189-L195
|
func ConfigGetBool(cluster *db.Cluster, key string) (bool, error) {
config, err := configGet(cluster)
if err != nil {
return false, err
}
return config.m.GetBool(key), nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L65-L73
|
func Versions(c context.Context, module string) ([]string, error) {
req := &pb.GetVersionsRequest{}
if module != "" {
req.Module = &module
}
res := &pb.GetVersionsResponse{}
err := internal.Call(c, "modules", "GetVersions", req, res)
return res.GetVersion(), err
}
|
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L256-L262
|
func (router *Router) OnGossip(update []byte) (GossipData, error) {
_, newUpdate, err := router.applyTopologyUpdate(update)
if err != nil || len(newUpdate) == 0 {
return nil, err
}
return &topologyGossipData{peers: router.Peers, update: newUpdate}, nil
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/plan.go#L36-L47
|
func (s *planService) Create(plan appTypes.Plan) error {
if plan.Name == "" {
return appTypes.PlanValidationError{Field: "name"}
}
if plan.CpuShare < 2 {
return appTypes.ErrLimitOfCpuShare
}
if plan.Memory > 0 && plan.Memory < 4194304 {
return appTypes.ErrLimitOfMemory
}
return s.storage.Insert(plan)
}
|
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/provisioner/provision_provider.go#L63-L96
|
func InitProvider(name string, configFilePath string) (Provisioner, error) {
var provider Provisioner
if name == "" {
logger.Get().Info("No providers specified.")
return nil, nil
}
var err error
if configFilePath != "" {
config, err := os.Open(configFilePath)
if err != nil {
logger.Get().Critical("Couldn't open auth provider configuration %s. error: %v",
configFilePath, err)
}
defer config.Close()
provider, err = GetProvider(name, config)
} else {
// Pass explicit nil so providers can actually check for nil. See
// "Why is my nil error value not equal to nil?" in golang.org/doc/faq.
provider, err = GetProvider(name, nil)
}
if err != nil {
return nil, fmt.Errorf("could not init plugin %s. error: %v", name, err)
}
if provider == nil {
return nil, fmt.Errorf("unknown plugin %s", name)
}
return provider, nil
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L235-L265
|
func generateEmpty(f *rule.File, regularFiles, genFiles []string) []*rule.Rule {
if f == nil {
return nil
}
knownFiles := make(map[string]bool)
for _, f := range regularFiles {
knownFiles[f] = true
}
for _, f := range genFiles {
knownFiles[f] = true
}
var empty []*rule.Rule
outer:
for _, r := range f.Rules {
if r.Kind() != "proto_library" {
continue
}
srcs := r.AttrStrings("srcs")
if len(srcs) == 0 && r.Attr("srcs") != nil {
// srcs is not a string list; leave it alone
continue
}
for _, src := range r.AttrStrings("srcs") {
if knownFiles[src] {
continue outer
}
}
empty = append(empty, rule.NewRule("proto_library", r.Name()))
}
return empty
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/httputil/httputil.go#L41-L50
|
func GetHostname(req *http.Request) string {
if req == nil {
return ""
}
h, _, err := net.SplitHostPort(req.Host)
if err != nil {
return req.Host
}
return h
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L42-L77
|
func storagePoolsGet(d *Daemon, r *http.Request) Response {
recursion := util.IsRecursionRequest(r)
pools, err := d.cluster.StoragePools()
if err != nil && err != db.ErrNoSuchObject {
return SmartError(err)
}
resultString := []string{}
resultMap := []api.StoragePool{}
for _, pool := range pools {
if !recursion {
resultString = append(resultString, fmt.Sprintf("/%s/storage-pools/%s", version.APIVersion, pool))
} else {
plID, pl, err := d.cluster.StoragePoolGet(pool)
if err != nil {
continue
}
// Get all users of the storage pool.
poolUsedBy, err := storagePoolUsedByGet(d.State(), plID, pool)
if err != nil {
return SmartError(err)
}
pl.UsedBy = poolUsedBy
resultMap = append(resultMap, *pl)
}
}
if !recursion {
return SyncResponse(true, resultString)
}
return SyncResponse(true, resultMap)
}
|
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/internal.go#L16-L48
|
func (b *Bench) internalRun(showProgress bool) results.ResultSet {
startTime := time.Now()
endTime := startTime.Add(b.duration)
sem := semaphore.NewSemaphore(b.threads, b.rampUp) // create a new semaphore with an initiall capacity or 0
out := make(chan results.Result)
resultsChan := make(chan []results.Result)
go handleResult(showProgress, out, resultsChan)
for run := true; run; run = (time.Now().Before(endTime)) {
sem.Lock() // blocks when channel is full
// execute a request
go doRequest(b.request, b.timeout, sem, out)
}
fmt.Print("\nWaiting for threads to finish ")
for i := sem.Length(); i != 0; i = sem.Length() {
//abandon <- true
time.Sleep(200 * time.Millisecond)
}
fmt.Println(" OK")
fmt.Println("")
close(out)
return <-resultsChan
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/easyjson.go#L82-L86
|
func (v *ResolveBlobReturns) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoIo(&r, v)
return r.Error()
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L113-L128
|
func GetContainers(c lxd.ContainerServer) ([]api.Container, error) {
containers := []api.Container{}
allContainers, err := c.GetContainers()
if err != nil {
return containers, err
}
for _, container := range allContainers {
if container.Config[userConfigKey] == "true" {
containers = append(containers, container)
}
}
return containers, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/log/types.go#L198-L218
|
func (t *Violation) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch Violation(in.String()) {
case ViolationLongTask:
*t = ViolationLongTask
case ViolationLongLayout:
*t = ViolationLongLayout
case ViolationBlockedEvent:
*t = ViolationBlockedEvent
case ViolationBlockedParser:
*t = ViolationBlockedParser
case ViolationDiscouragedAPIUse:
*t = ViolationDiscouragedAPIUse
case ViolationHandler:
*t = ViolationHandler
case ViolationRecurringHandler:
*t = ViolationRecurringHandler
default:
in.AddError(errors.New("unknown Violation value"))
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L854-L902
|
func (s *storageCeph) copyWithSnapshots(sourceVolumeName string,
targetVolumeName string, sourceParentSnapshot string) error {
logger.Debugf(`Creating non-sparse copy of RBD storage volume "%s to "%s"`, sourceVolumeName, targetVolumeName)
args := []string{
"export-diff",
"--id", s.UserName,
"--cluster", s.ClusterName,
sourceVolumeName,
}
if sourceParentSnapshot != "" {
args = append(args, "--from-snap", sourceParentSnapshot)
}
// redirect output to stdout
args = append(args, "-")
rbdSendCmd := exec.Command("rbd", args...)
rbdRecvCmd := exec.Command(
"rbd",
"--id", s.UserName,
"import-diff",
"--cluster", s.ClusterName,
"-",
targetVolumeName)
rbdRecvCmd.Stdin, _ = rbdSendCmd.StdoutPipe()
rbdRecvCmd.Stdout = os.Stdout
rbdRecvCmd.Stderr = os.Stderr
err := rbdRecvCmd.Start()
if err != nil {
return err
}
err = rbdSendCmd.Run()
if err != nil {
return err
}
err = rbdRecvCmd.Wait()
if err != nil {
return err
}
logger.Debugf(`Created non-sparse copy of RBD storage volume "%s" to "%s"`, sourceVolumeName, targetVolumeName)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/types.go#L69-L71
|
func (t *WindowState) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2726-L2729
|
func (e PathPaymentResultCode) ValidEnum(v int32) bool {
_, ok := pathPaymentResultCodeMap[v]
return ok
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L888-L891
|
func (c *Cluster) ImageUploadedAt(id int, uploadedAt time.Time) error {
err := exec(c.db, "UPDATE images SET upload_date=? WHERE id=?", uploadedAt, id)
return err
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/crier/controller.go#L78-L125
|
func (c *Controller) Run(stopCh <-chan struct{}) {
// handle a panic with logging and exiting
defer utilruntime.HandleCrash()
// ignore new items in the queue but when all goroutines
// have completed existing items then shutdown
defer c.queue.ShutDown()
logrus.Info("Initiating controller")
c.informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
logrus.WithField("prowjob", key).Infof("Add prowjob")
if err != nil {
logrus.WithError(err).Error("Cannot get key from object meta")
return
}
c.queue.AddRateLimited(key)
},
UpdateFunc: func(oldObj, newObj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(newObj)
logrus.WithField("prowjob", key).Infof("Update prowjob")
if err != nil {
logrus.WithError(err).Error("Cannot get key from object meta")
return
}
c.queue.AddRateLimited(key)
},
})
// run the informer to start listing and watching resources
go c.informer.Informer().Run(stopCh)
// do the initial synchronization (one time) to populate resources
if !cache.WaitForCacheSync(stopCh, c.HasSynced) {
utilruntime.HandleError(fmt.Errorf("Error syncing cache"))
return
}
logrus.Info("Controller.Run: cache sync complete")
// run the runWorker method every second with a stop channel
for i := 0; i < c.numWorkers; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
}
logrus.Infof("Started %d workers", c.numWorkers)
<-stopCh
logrus.Info("Shutting down workers")
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/content_type_checker.go#L16-L40
|
func (mw *ContentTypeCheckerMiddleware) MiddlewareFunc(handler HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
mediatype, params, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
charset, ok := params["charset"]
if !ok {
charset = "UTF-8"
}
// per net/http doc, means that the length is known and non-null
if r.ContentLength > 0 &&
!(mediatype == "application/json" && strings.ToUpper(charset) == "UTF-8") {
Error(w,
"Bad Content-Type or charset, expected 'application/json'",
http.StatusUnsupportedMediaType,
)
return
}
// call the wrapped handler
handler(w, r)
}
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L489-L492
|
func NewCameraCapture(index int) *Capture {
cap := C.cvCreateCameraCapture(C.int(index))
return (*Capture)(cap)
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L613-L651
|
func (c *Connection) readFrames(_ uint32) {
headerBuf := make([]byte, FrameHeaderSize)
handleErr := func(err error) {
if !c.closeNetworkCalled.Load() {
c.connectionError("read frames", err)
} else {
c.log.Debugf("Ignoring error after connection was closed: %v", err)
}
}
for {
// Read the header, avoid allocating the frame till we know the size
// we need to allocate.
if _, err := io.ReadFull(c.conn, headerBuf); err != nil {
handleErr(err)
return
}
frame := c.opts.FramePool.Get()
if err := frame.ReadBody(headerBuf, c.conn); err != nil {
handleErr(err)
c.opts.FramePool.Release(frame)
return
}
c.updateLastActivity(frame)
var releaseFrame bool
if c.relay == nil {
releaseFrame = c.handleFrameNoRelay(frame)
} else {
releaseFrame = c.handleFrameRelay(frame)
}
if releaseFrame {
c.opts.FramePool.Release(frame)
}
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5612-L5621
|
func (u ScpHistoryEntry) GetV0() (result ScpHistoryEntryV0, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.V))
if armName == "V0" {
result = *u.V0
ok = true
}
return
}
|
https://github.com/reiver/go-telnet/blob/9ff0b2ab096ebe42bf8e2ffd1366e7ed2223b04c/data_reader.go#L65-L74
|
func newDataReader(r io.Reader) *internalDataReader {
buffered := bufio.NewReader(r)
reader := internalDataReader{
wrapped:r,
buffered:buffered,
}
return &reader
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L648-L686
|
func (v *VM) CreateSnapshot(name, description string, options CreateSnapshotOption) (*Snapshot, error) {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var snapshotHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
sname := C.CString(name)
sdesc := C.CString(description)
defer C.free(unsafe.Pointer(sname))
defer C.free(unsafe.Pointer(sdesc))
jobHandle = C.VixVM_CreateSnapshot(v.handle,
sname, // name
sdesc, // description
C.VixCreateSnapshotOptions(options), // options
C.VIX_INVALID_HANDLE, // propertyListHandle
nil, // callbackProc
nil) // clientData
err = C.get_vix_handle(jobHandle,
C.VIX_PROPERTY_JOB_RESULT_HANDLE,
&snapshotHandle,
C.VIX_PROPERTY_NONE)
if C.VIX_OK != err {
return nil, &Error{
Operation: "vm.CreateSnapshot",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
snapshot := &Snapshot{
handle: snapshotHandle,
}
runtime.SetFinalizer(snapshot, cleanupSnapshot)
return snapshot, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pluginhelp/hook/hook.go#L145-L178
|
func (ha *HelpAgent) GeneratePluginHelp() *pluginhelp.Help {
config := ha.pa.Config()
orgToRepos := ha.oa.orgToReposMap(config)
normalRevMap, externalRevMap := reversePluginMaps(config, orgToRepos)
allPlugins, pluginHelp := ha.generateNormalPluginHelp(config, normalRevMap)
allExternalPlugins, externalPluginHelp := ha.generateExternalPluginHelp(config, externalRevMap)
// Load repo->plugins maps from config
repoPlugins := map[string][]string{
"": allPlugins,
}
for repo, plugins := range config.Plugins {
repoPlugins[repo] = plugins
}
repoExternalPlugins := map[string][]string{
"": allExternalPlugins,
}
for repo, exts := range config.ExternalPlugins {
for _, ext := range exts {
repoExternalPlugins[repo] = append(repoExternalPlugins[repo], ext.Name)
}
}
return &pluginhelp.Help{
AllRepos: allRepos(config, orgToRepos),
RepoPlugins: repoPlugins,
RepoExternalPlugins: repoExternalPlugins,
PluginHelp: pluginHelp,
ExternalPluginHelp: externalPluginHelp,
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L141-L145
|
func (v TouchPoint) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoInput(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/picker/roundrobin_balanced.go#L28-L40
|
func NewRoundrobinBalanced(
lg *zap.Logger,
scs []balancer.SubConn,
addrToSc map[resolver.Address]balancer.SubConn,
scToAddr map[balancer.SubConn]resolver.Address,
) Picker {
return &rrBalanced{
lg: lg,
scs: scs,
addrToSc: addrToSc,
scToAddr: scToAddr,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1275-L1284
|
func (c *Client) CreateStatus(org, repo, SHA string, s Status) error {
c.log("CreateStatus", org, repo, SHA, s)
_, err := c.request(&request{
method: http.MethodPost,
path: fmt.Sprintf("/repos/%s/%s/statuses/%s", org, repo, SHA),
requestBody: &s,
exitCodes: []int{201},
}, nil)
return err
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/memory.go#L54-L58
|
func (i *memoryImage) Signatures(ctx context.Context) ([][]byte, error) {
// Modifying an image invalidates signatures; a caller asking the updated image for signatures
// is probably confused.
return nil, errors.New("Internal error: Image.Signatures() is not supported for images modified in memory")
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_header.go#L77-L83
|
func (c headerCtx) SetResponseHeaders(headers map[string]string) {
if h := c.headers(); h != nil {
h.respHeaders = headers
return
}
panic("SetResponseHeaders called on ContextWithHeaders not created via WrapWithHeaders")
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L296-L298
|
func (l *Logger) Println(args ...interface{}) {
l.Output(2, LevelTrace, fmt.Sprintln(args...))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migration/wsproto.go#L14-L35
|
func ProtoRecv(ws *websocket.Conn, msg proto.Message) error {
mt, r, err := ws.NextReader()
if err != nil {
return err
}
if mt != websocket.BinaryMessage {
return fmt.Errorf("Only binary messages allowed")
}
buf, err := ioutil.ReadAll(r)
if err != nil {
return err
}
err = proto.Unmarshal(buf, msg)
if err != nil {
return err
}
return nil
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L322-L332
|
func (win *Window) Destroy() {
C.cvDestroyWindow(win.name_c)
delete(allWindows, win.name)
for _, bar_name := range win.trackbarName {
C.GoOpenCV_DestroyTrackbar(bar_name, win.name_c)
C.free(unsafe.Pointer(bar_name))
}
C.free(unsafe.Pointer(win.name_c))
win.name_c = nil
}
|
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/nodefilter.go#L36-L44
|
func NewNodeChanFilter(text <-chan string) DirtyFilter {
nf := &nodeFilter{
root: newNode(),
}
for v := range text {
nf.addDirtyWords(v)
}
return nf
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L358-L361
|
func (p EvaluateParams) WithGeneratePreview(generatePreview bool) *EvaluateParams {
p.GeneratePreview = generatePreview
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3102-L3106
|
func (v Property) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss27(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/senseyeio/roger/blob/5a944f2c5ceb5139f926c5ae134202ec2abba71a/assign/factory.go#L6-L25
|
func Assign(symbol string, value interface{}) ([]byte, error) {
switch value.(type) {
case []float64:
return assignDoubleArray(symbol, value.([]float64))
case []int32:
return assignIntArray(symbol, value.([]int32))
case []string:
return assignStrArray(symbol, value.([]string))
case []byte:
return assignByteArray(symbol, value.([]byte))
case string:
return assignStr(symbol, value.(string))
case int32:
return assignInt(symbol, value.(int32))
case float64:
return assignDouble(symbol, value.(float64))
default:
return nil, errors.New("session assign: type is not supported")
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L481-L548
|
func renameTop(f *ast.File, old, new string) bool {
var fixed bool
// Rename any conflicting imports
// (assuming package name is last element of path).
for _, s := range f.Imports {
if s.Name != nil {
if s.Name.Name == old {
s.Name.Name = new
fixed = true
}
} else {
_, thisName := path.Split(importPath(s))
if thisName == old {
s.Name = ast.NewIdent(new)
fixed = true
}
}
}
// Rename any top-level declarations.
for _, d := range f.Decls {
switch d := d.(type) {
case *ast.FuncDecl:
if d.Recv == nil && d.Name.Name == old {
d.Name.Name = new
d.Name.Obj.Name = new
fixed = true
}
case *ast.GenDecl:
for _, s := range d.Specs {
switch s := s.(type) {
case *ast.TypeSpec:
if s.Name.Name == old {
s.Name.Name = new
s.Name.Obj.Name = new
fixed = true
}
case *ast.ValueSpec:
for _, n := range s.Names {
if n.Name == old {
n.Name = new
n.Obj.Name = new
fixed = true
}
}
}
}
}
}
// Rename top-level old to new, both unresolved names
// (probably defined in another file) and names that resolve
// to a declaration we renamed.
walk(f, func(n interface{}) {
id, ok := n.(*ast.Ident)
if ok && isTopName(id, old) {
id.Name = new
fixed = true
}
if ok && id.Obj != nil && id.Name == old && id.Obj.Name == new {
id.Name = id.Obj.Name
fixed = true
}
})
return fixed
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/wal.go#L583-L667
|
func (w *WAL) cut() error {
// close old wal file; truncate to avoid wasting space if an early cut
off, serr := w.tail().Seek(0, io.SeekCurrent)
if serr != nil {
return serr
}
if err := w.tail().Truncate(off); err != nil {
return err
}
if err := w.sync(); err != nil {
return err
}
fpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1))
// create a temp wal file with name sequence + 1, or truncate the existing one
newTail, err := w.fp.Open()
if err != nil {
return err
}
// update writer and save the previous crc
w.locks = append(w.locks, newTail)
prevCrc := w.encoder.crc.Sum32()
w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
if err != nil {
return err
}
if err = w.saveCrc(prevCrc); err != nil {
return err
}
if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
return err
}
if err = w.saveState(&w.state); err != nil {
return err
}
// atomically move temp wal file to wal file
if err = w.sync(); err != nil {
return err
}
off, err = w.tail().Seek(0, io.SeekCurrent)
if err != nil {
return err
}
if err = os.Rename(newTail.Name(), fpath); err != nil {
return err
}
if err = fileutil.Fsync(w.dirFile); err != nil {
return err
}
// reopen newTail with its new path so calls to Name() match the wal filename format
newTail.Close()
if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
return err
}
if _, err = newTail.Seek(off, io.SeekStart); err != nil {
return err
}
w.locks[len(w.locks)-1] = newTail
prevCrc = w.encoder.crc.Sum32()
w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
if err != nil {
return err
}
if w.lg != nil {
w.lg.Info("created a new WAL segment", zap.String("path", fpath))
} else {
plog.Infof("segmented wal file %v is created", fpath)
}
return nil
}
|
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/pbuf.go#L159-L172
|
func (b *PointerRingBuf) Adopt(me []interface{}) {
n := len(me)
if n > b.N {
b.A = me
b.N = n
b.Beg = 0
b.Readable = n
} else {
// we already have a larger buffer, reuse it.
copy(b.A, me)
b.Beg = 0
b.Readable = n
}
}
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L341-L343
|
func (l *Logger) Infoln(args ...interface{}) {
l.Output(2, LevelInfo, fmt.Sprintln(args...))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1016-L1020
|
func (v GetVersionParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser10(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/iterator.go#L485-L505
|
func (s *ConcatIterator) Seek(key []byte) {
var idx int
if !s.reversed {
idx = sort.Search(len(s.tables), func(i int) bool {
return y.CompareKeys(s.tables[i].Biggest(), key) >= 0
})
} else {
n := len(s.tables)
idx = n - 1 - sort.Search(n, func(i int) bool {
return y.CompareKeys(s.tables[n-1-i].Smallest(), key) <= 0
})
}
if idx >= len(s.tables) || idx < 0 {
s.setIdx(-1)
return
}
// For reversed=false, we know s.tables[i-1].Biggest() < key. Thus, the
// previous table cannot possibly contain key.
s.setIdx(idx)
s.cur.Seek(key)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L248-L257
|
func getCompareFailCause(n *node, which int, prevValue string, prevIndex uint64) string {
switch which {
case CompareIndexNotMatch:
return fmt.Sprintf("[%v != %v]", prevIndex, n.ModifiedIndex)
case CompareValueNotMatch:
return fmt.Sprintf("[%v != %v]", prevValue, n.Value)
default:
return fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, n.Value, prevIndex, n.ModifiedIndex)
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L14776-L14778
|
func (api *API) VolumeSnapshotLocator(href string) *VolumeSnapshotLocator {
return &VolumeSnapshotLocator{Href(href), api}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2393-L2397
|
func (v SelectorList) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss22(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/server.go#L76-L83
|
func RegisterHandlerVersion(version, path, method string, h http.Handler) {
var th TsuruHandler
th.version = version
th.path = path
th.method = method
th.h = h
tsuruHandlerList = append(tsuruHandlerList, th)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2729-L2733
|
func (v MoveToParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom30(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L255-L267
|
func (t *Throttle) Do() error {
for {
select {
case t.ch <- struct{}{}:
t.wg.Add(1)
return nil
case err := <-t.errCh:
if err != nil {
return err
}
}
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1559-L1563
|
func (v *RemoveAttributeParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom16(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L164-L168
|
func (c *SubChannel) StatsTags() map[string]string {
tags := c.topChannel.StatsTags()
tags["subchannel"] = c.serviceName
return tags
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1518-L1597
|
func swap(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
app1Name := InputValue(r, "app1")
app2Name := InputValue(r, "app2")
forceSwap := InputValue(r, "force")
cnameOnly, _ := strconv.ParseBool(InputValue(r, "cnameOnly"))
if forceSwap == "" {
forceSwap = "false"
}
locked1, err := app.AcquireApplicationLockWait(app1Name, t.GetUserName(), "/swap", lockWaitDuration)
if err != nil {
return err
}
defer app.ReleaseApplicationLock(app1Name)
locked2, err := app.AcquireApplicationLockWait(app2Name, t.GetUserName(), "/swap", lockWaitDuration)
if err != nil {
return err
}
defer app.ReleaseApplicationLock(app2Name)
app1, err := getApp(app1Name)
if err != nil {
return err
}
if !locked1 {
return &errors.HTTP{Code: http.StatusConflict, Message: fmt.Sprintf("%s: %s", app1.Name, &app1.Lock)}
}
app2, err := getApp(app2Name)
if err != nil {
return err
}
if !locked2 {
return &errors.HTTP{Code: http.StatusConflict, Message: fmt.Sprintf("%s: %s", app2.Name, &app2.Lock)}
}
allowed1 := permission.Check(t, permission.PermAppUpdateSwap,
contextsForApp(app1)...,
)
allowed2 := permission.Check(t, permission.PermAppUpdateSwap,
contextsForApp(app2)...,
)
if !allowed1 || !allowed2 {
return permission.ErrUnauthorized
}
evt, err := event.New(&event.Opts{
Target: appTarget(app1Name),
ExtraTargets: []event.ExtraTarget{
{Target: appTarget(app2Name), Lock: true},
},
Kind: permission.PermAppUpdateSwap,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(app1)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
// compare apps by platform type and number of units
if forceSwap == "false" {
if app1.Platform != app2.Platform {
return &errors.HTTP{
Code: http.StatusPreconditionFailed,
Message: "platforms don't match",
}
}
app1Units, err := app1.Units()
if err != nil {
return err
}
app2Units, err := app2.Units()
if err != nil {
return err
}
if len(app1Units) != len(app2Units) {
return &errors.HTTP{
Code: http.StatusPreconditionFailed,
Message: "number of units doesn't match",
}
}
}
return app.Swap(app1, app2, cnameOnly)
}
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/exit_matcher.go#L23-L32
|
func Exit(optionalExitCode ...int) *exitMatcher {
exitCode := -1
if len(optionalExitCode) > 0 {
exitCode = optionalExitCode[0]
}
return &exitMatcher{
exitCode: exitCode,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/clonerefs/options.go#L194-L197
|
func (r *stringSlice) Set(value string) error {
r.data = append(r.data, value)
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L15-L18
|
func MetadataFromIncomingContext(ctx context.Context) metadata.MD {
md, _ := metadata.FromIncomingContext(ctx)
return md
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/auto.go#L65-L84
|
func (e *Engine) Auto(ctx context.Context, i interface{}) Renderer {
ct, _ := ctx.Value("contentType").(string)
if ct == "" {
ct = e.DefaultContentType
}
ct = strings.TrimSpace(strings.ToLower(ct))
if strings.Contains(ct, "json") {
return e.JSON(i)
}
if strings.Contains(ct, "xml") {
return e.XML(i)
}
return htmlAutoRenderer{
Engine: e,
model: i,
}
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L178-L251
|
func (s *Storage) List(ctx context.Context, offset, limit int64, expiredAtFrom, expiredAtTo *time.Time) ([]*mnemosynerpc.Session, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "postgres.storage.list")
defer span.Finish()
if limit == 0 {
return nil, errors.New("cannot retrieve list of sessions, limit needs to be higher than 0")
}
args := []interface{}{offset, limit}
query := "SELECT access_token, refresh_token, subject_id, subject_client, bag, expire_at FROM " + s.schema + "." + s.table + " "
if expiredAtFrom != nil || expiredAtTo != nil {
query += " WHERE "
}
switch {
case expiredAtFrom != nil && expiredAtTo == nil:
query += "expire_at > $3"
args = append(args, expiredAtFrom)
case expiredAtFrom == nil && expiredAtTo != nil:
query += "expire_at < $3"
args = append(args, expiredAtTo)
case expiredAtFrom != nil && expiredAtTo != nil:
query += "expire_at > $3 AND expire_at < $4"
args = append(args, expiredAtFrom, expiredAtTo)
}
query += " OFFSET $1 LIMIT $2"
labels := prometheus.Labels{"query": "list"}
start := time.Now()
rows, err := s.db.QueryContext(ctx, query, args...)
s.incQueries(labels, start)
if err != nil {
s.incError(labels)
return nil, err
}
defer rows.Close()
sessions := make([]*mnemosynerpc.Session, 0, limit)
for rows.Next() {
var ent sessionEntity
err = rows.Scan(
&ent.AccessToken,
&ent.RefreshToken,
&ent.SubjectID,
&ent.SubjectClient,
&ent.Bag,
&ent.ExpireAt,
)
if err != nil {
s.incError(labels)
return nil, err
}
expireAt, err := ptypes.TimestampProto(ent.ExpireAt)
if err != nil {
return nil, err
}
sessions = append(sessions, &mnemosynerpc.Session{
AccessToken: ent.AccessToken,
RefreshToken: ent.RefreshToken,
SubjectId: ent.SubjectID,
SubjectClient: ent.SubjectClient,
Bag: ent.Bag,
ExpireAt: expireAt,
})
}
if rows.Err() != nil {
s.incError(labels)
return nil, rows.Err()
}
return sessions, nil
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L71-L78
|
func remapError(err error) error {
if e, ok := err.(*internal.APIError); ok {
if e.Service == "xmpp" {
e.Service = "channel"
}
}
return err
}
|
https://github.com/libp2p/go-libp2p-routing/blob/15c28e7faa25921fd1160412003fecdc70e09a5c/notifications/query.go#L44-L52
|
func (e *eventChannel) waitThenClose() {
<-e.ctx.Done()
e.mu.Lock()
close(e.ch)
// 1. Signals that we're done.
// 2. Frees memory (in case we end up hanging on to this for a while).
e.ch = nil
e.mu.Unlock()
}
|
https://github.com/blacksails/cgp/blob/570ac705cf2d7a9235d911d00b6f976ab3386c2f/domain.go#L17-L27
|
func (dom Domain) Exists() (bool, error) {
var d dictionary
err := dom.cgp.request(getDomainSettings{Domain: dom.Name}, &d)
if _, ok := err.(SOAPNotFoundError); ok {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L220-L237
|
func (r *Raft) liveBootstrap(configuration Configuration) error {
// Use the pre-init API to make the static updates.
err := BootstrapCluster(&r.conf, r.logs, r.stable, r.snapshots,
r.trans, configuration)
if err != nil {
return err
}
// Make the configuration live.
var entry Log
if err := r.logs.GetLog(1, &entry); err != nil {
panic(err)
}
r.setCurrentTerm(1)
r.setLastLog(entry.Index, entry.Term)
r.processConfigurationLogEntry(&entry)
return nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log_debug.go#L33-L39
|
func Debug(msg string, ctx ...interface{}) {
if Log != nil {
pc, fn, line, _ := runtime.Caller(1)
msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg)
Log.Debug(msg, ctx...)
}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/namespace/kv.go#L32-L34
|
func NewKV(kv clientv3.KV, prefix string) clientv3.KV {
return &kvPrefix{kv, prefix}
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/servers/servers.go#L23-L29
|
func WrapTLS(s *http.Server, certFile string, keyFile string) Server {
return &TLS{
Server: s,
CertFile: certFile,
KeyFile: keyFile,
}
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/innkeeperclient/fake/ik_client.go#L54-L57
|
func (s *IKClient) DeProvisionHost(requestID string) (resp *innkeeperclient.GetStatusResponse, err error) {
s.SpyRequestID = requestID
return nil, s.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L569-L602
|
func serviceInstanceProxy(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
serviceName := r.URL.Query().Get(":service")
instanceName := r.URL.Query().Get(":instance")
serviceInstance, err := getServiceInstanceOrError(serviceName, instanceName)
if err != nil {
return err
}
allowed := permission.Check(t, permission.PermServiceInstanceUpdateProxy,
contextsForServiceInstance(serviceInstance, serviceName)...,
)
if !allowed {
return permission.ErrUnauthorized
}
path := r.URL.Query().Get("callback")
var evt *event.Event
if r.Method != http.MethodGet && r.Method != http.MethodHead {
evt, err = event.New(&event.Opts{
Target: serviceInstanceTarget(serviceName, instanceName),
Kind: permission.PermServiceInstanceUpdateProxy,
Owner: t,
CustomData: append(event.FormToCustomData(InputFields(r)), map[string]interface{}{
"name": "method",
"value": r.Method,
}),
Allowed: event.Allowed(permission.PermServiceInstanceReadEvents,
contextsForServiceInstance(serviceInstance, serviceName)...),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
}
return service.ProxyInstance(serviceInstance, path, evt, requestIDHeader(r), w, r)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/dump.go#L16-L62
|
func Dump(tx *sql.Tx, schema string, schemaOnly bool) (string, error) {
schemas := dumpParseSchema(schema)
// Begin
dump := `PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
`
// Schema table
tableDump, err := dumpTable(tx, "schema", dumpSchemaTable)
if err != nil {
return "", errors.Wrapf(err, "failed to dump table schema")
}
dump += tableDump
// All other tables
tables := make([]string, 0)
for table := range schemas {
tables = append(tables, table)
}
sort.Strings(tables)
for _, table := range tables {
if schemaOnly {
// Dump only the schema.
dump += schemas[table] + "\n"
continue
}
tableDump, err := dumpTable(tx, table, schemas[table])
if err != nil {
return "", errors.Wrapf(err, "failed to dump table %s", table)
}
dump += tableDump
}
// Sequences (unless the schemaOnly flag is true)
if !schemaOnly {
tableDump, err = dumpTable(tx, "sqlite_sequence", "DELETE FROM sqlite_sequence;")
if err != nil {
return "", errors.Wrapf(err, "failed to dump table sqlite_sequence")
}
dump += tableDump
}
// Commit
dump += "COMMIT;\n"
return dump, nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L573-L585
|
func (p *Peer) NumPendingOutbound() int {
count := 0
p.RLock()
for _, c := range p.outboundConnections {
count += c.outbound.count()
}
for _, c := range p.inboundConnections {
count += c.outbound.count()
}
p.RUnlock()
return count
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L702-L704
|
func SubScalar(src *IplImage, value Scalar, dst *IplImage) {
SubScalarWithMask(src, value, dst, nil)
}
|
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L176-L201
|
func (g *Guest) RmDir(path string) error {
var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE
var err C.VixError = C.VIX_OK
cpath := C.CString(path)
defer C.free(unsafe.Pointer(cpath))
jobHandle = C.VixVM_DeleteDirectoryInGuest(g.handle,
cpath, // path name
0, // options
nil, // callbackProc
nil) // clientData
defer C.Vix_ReleaseHandle(jobHandle)
err = C.vix_job_wait(jobHandle)
if C.VIX_OK != err {
return &Error{
Operation: "guest.RmDir",
Code: int(err & 0xFFFF),
Text: C.GoString(C.Vix_GetErrorText(err, nil)),
}
}
return nil
}
|
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/cedar.go#L228-L242
|
func (da *cedar) pushSibling(from, base int, label byte, hasChild bool) {
c := &da.Ninfos[from].Child
keepOrder := *c == 0
if da.Ordered {
keepOrder = label > *c
}
if hasChild && keepOrder {
c = &da.Ninfos[base^int(*c)].Sibling
for da.Ordered && *c != 0 && *c < label {
c = &da.Ninfos[base^int(*c)].Sibling
}
}
da.Ninfos[base^int(label)].Sibling = *c
*c = label
}
|
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L215-L224
|
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
ret, offset, err = _parseBase128Int(bytes, initOffset)
if offset-initOffset >= 4 {
err = asn1.StructuralError{Msg: "base 128 integer too large"}
return
}
return
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/transaction.go#L32-L39
|
func rollback(tx *sql.Tx, reason error) error {
err := tx.Rollback()
if err != nil {
logger.Warnf("Failed to rollback transaction after error (%v): %v", reason, err)
}
return reason
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistries/system_registries.go#L93-L103
|
func RegistriesConfPath(ctx *types.SystemContext) string {
path := systemRegistriesConfPath
if ctx != nil {
if ctx.SystemRegistriesConfPath != "" {
path = ctx.SystemRegistriesConfPath
} else if ctx.RootForImplicitAbsolutePaths != "" {
path = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath)
}
}
return path
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L290-L300
|
func (config *directClientConfig) ConfirmUsable() error {
var validationErrors []error
validationErrors = append(validationErrors, validateAuthInfo(config.getAuthInfoName(), config.getAuthInfo())...)
validationErrors = append(validationErrors, validateClusterInfo(config.getClusterName(), config.getCluster())...)
// when direct client config is specified, and our only error is that no server is defined, we should
// return a standard "no config" error
if len(validationErrors) == 1 && validationErrors[0] == errEmptyCluster {
return newErrConfigurationInvalid([]error{errEmptyConfig})
}
return newErrConfigurationInvalid(validationErrors)
}
|
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/group.go#L35-L40
|
func NewGroup() *Group {
return &Group{
controllers: make(map[string]*Controller),
actions: make(map[string]*GroupAction),
}
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L168-L173
|
func (l Label) Equal(other Label) bool {
return l.Repo == other.Repo &&
l.Pkg == other.Pkg &&
l.Name == other.Name &&
l.Relative == other.Relative
}
|
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/run/showcmd.go#L28-L45
|
func (s *ShowCmd) All(w io.Writer) error {
if filepath.Ext(s.release) == ".pivotal" {
pivnetRelease, err := release.LoadPivnetRelease(s.releaseRepo, s.release)
if err != nil {
return err
}
for _, br := range pivnetRelease.BoshRelease {
s.printBoshRelease(w, br)
}
return nil
}
boshRelease, err := release.LoadBoshRelease(s.releaseRepo, s.release)
if err != nil {
return err
}
s.printBoshRelease(w, boshRelease)
return nil
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/path.go#L231-L236
|
func (si SliceIndex) Key() int {
if si.xkey != si.ykey {
return -1
}
return si.xkey
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_transport.go#L126-L136
|
func (i *InmemTransport) InstallSnapshot(id ServerID, target ServerAddress, args *InstallSnapshotRequest, resp *InstallSnapshotResponse, data io.Reader) error {
rpcResp, err := i.makeRPC(target, args, data, 10*i.timeout)
if err != nil {
return err
}
// Copy the result back
out := rpcResp.Response.(*InstallSnapshotResponse)
*resp = *out
return nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L63-L76
|
func (i *InmemStore) StoreLogs(logs []*Log) error {
i.l.Lock()
defer i.l.Unlock()
for _, l := range logs {
i.logs[l.Index] = l
if i.lowIndex == 0 {
i.lowIndex = l.Index
}
if l.Index > i.highIndex {
i.highIndex = l.Index
}
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.