Dataset Viewer
Auto-converted to Parquet Duplicate
input
stringlengths
24
2.11k
output
stringlengths
7
948
package augeas import "C" import ( "fmt" ) type ErrorCode int const ( CouldNotInitialize ErrorCode = -2 NoMatch = -1 NoError = 0 ENOMEM EINTERNAL EPATHX ENOMATCH EMMATCH ESYNTAX ENOLENS EMXFM ENOSPAN EMVDESC ECMDRUN EBADARG ) type Error struct { Code ErrorCo...
{ return C.GoString(C.aug_error_details(a.handle)) }
package circleci import ( "log" "testing" "github.com/stretchr/testify/assert" ) func TestRecentBuilds(t *testing.T)
{ c := setup() builds := c.RecentBuilds("ryanlower", "go-circleci") log.Print(builds) lastBuild := builds[0] assert.Equal(t, lastBuild.Branch, "master") assert.Equal(t, lastBuild.Status, "running") }
package names import "knative.dev/pkg/kmeta" func Deployment(rev kmeta.Accessor) string { return kmeta.ChildName(rev.GetName(), "-deployment") } func ImageCache(rev kmeta.Accessor) string { return kmeta.ChildName(rev.GetName(), "-cache") } func PA(rev kmeta.Accessor) string
{ return rev.GetName() }
package dataflow import ( "context" "strconv" "time" "go-common/app/interface/main/app-interface/conf" "go-common/library/log" "go-common/library/log/infoc" ) type Service struct { c *conf.Config infoc *infoc.Infoc } func New(c *conf.Config) (s *Service) { s = &Service{ c: c, infoc: infoc.New...
{ if err = s.infoc.Info(strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo); err != nil { log.Error("s.infoc2.Info(%v,%v,%v,%v,%v,%v) error(%v)", strconv.FormatInt(now.Unix(), 10), eventID, eventType, buvid, fts, messageInfo, err) } return }
package http import ( "net/url" "os" "testing" ) var cacheKeysTests = []struct { proxy string scheme string addr string key string }{ {"", "http", "foo.com", "|http|foo.com"}, {"", "https", "foo.com", "|https|foo.com"}, {"http://foo.com", "http", "foo.com", "http://foo.com|http|"}, {"http://foo.co...
{ for _, tt := range cacheKeysTests { var proxy *url.URL if tt.proxy != "" { u, err := url.Parse(tt.proxy) if err != nil { t.Fatal(err) } proxy = u } cm := connectMethod{proxyURL: proxy, targetScheme: tt.scheme, targetAddr: tt.addr} if got := cm.key().String(); got != tt.key { t.Fatalf("{%...
package future import ( "time" ) const FuelRechargeRate = float32(1.0 / 3.0) func CannonX(initial float32, rate float32, elap time.Duration) (float32, float32) { x := initial + rate*float32(elap)/float32(time.Second) switch { case x < 0: x = -x rate = -rate case x > 1: x = 2 - x rate = -rate } r...
{ fuel := initial + FuelRechargeRate*float32(elap)/float32(time.Second) if fuel > 10 { fuel = 10 } return fuel }
package main var x int func f()
{ L1: for { } L2: select { } L3: switch { } L4: if true { } L5: f() L6: f() L6: f() if x == 20 { goto L6 } L7: for { break L7 } L8: for { if x == 21 { continue L8 } } L9: switch { case true: break L9 defalt: } L10: select { default: break L10 } }
package wca import ( "unsafe" ) type IAudioClient2 struct { IAudioClient } type IAudioClient2Vtbl struct { IAudioClientVtbl IsOffloadCapable uintptr SetClientProperties uintptr GetBufferSizeLimits uintptr } func (v *IAudioClient2) IsOffloadCapable(category uint32, isOffloadCapable *bool) (err error) {...
{ return (*IAudioClient2Vtbl)(unsafe.Pointer(v.RawVTable)) }
package main import "fmt" func main() { x := 1.5 square(&x) fmt.Println(x) } func square(x *float64)
{ *x = *x * *x }
package jsoniter import ( "github.com/stretchr/testify/require" "testing" ) func Test_encode_optional_int_pointer(t *testing.T) { should := require.New(t) var ptr *int str, err := MarshalToString(ptr) should.Nil(err) should.Equal("null", str) val := 100 ptr = &val str, err = MarshalToString(ptr) should.Nil...
{ should := require.New(t) type TestObject struct { Field1 *string Field2 *string } obj := TestObject{} UnmarshalFromString(`{"field1": null, "field2": "world"}`, &obj) should.Nil(obj.Field1) should.Equal("world", *obj.Field2) }
package apm import ( "fmt" ) type KeyTransaction struct { ID int `json:"id,omitempty"` Name string `json:"name,omitempty"` TransactionName string `json:"transaction_name,omitempty"` HealthStatus string `jso...
{ results := []*KeyTransaction{} nextURL := a.config.Region().RestURL("key_transactions.json") for nextURL != "" { response := keyTransactionsResponse{} resp, err := a.client.Get(nextURL, &params, &response) if err != nil { return nil, err } results = append(results, response.KeyTransactions...) p...
package main import . "g2d" var screen = Point{480, 360} var size = Point{20, 20} type Ball struct { x, y int dx, dy int } func NewBall(pos Point) *Ball { return &Ball{pos.X, pos.Y, 5, 5} } func (b *Ball) Move() { if !(0 <= b.x+b.dx && b.x+b.dx <= screen.X-size.X) { b.dx = -b.dx } ...
{ for i := 0; i < 25; i++ { Println("Ball 1 @", b1.Position()) Println("Ball 2 @", b2.Position()) b1.Move() b2.Move() } }
package middleware import ( "github.com/drone/drone/shared/model" "github.com/zenazn/goji/web" ) func UserToC(c *web.C, user *model.User) { c.Env["user"] = user } func RepoToC(c *web.C, repo *model.Repo) { c.Env["repo"] = repo } func RoleToC(c *web.C, role *model.Perm) { c.Env["role"] = role } func T...
{ var v = c.Env["repo"] if v == nil { return nil } r, ok := v.(*model.Repo) if !ok { return nil } return r }
package elastic type LimitFilter struct { Filter limit int } func (f LimitFilter) Source() interface{} { source := make(map[string]interface{}) params := make(map[string]interface{}) source["limit"] = params params["value"] = f.limit return source } func NewL...
{ f := LimitFilter{limit: limit} return f }
package gospec import ( "fmt" filepath "path" "runtime" ) type Location struct { name string file string line int } func currentLocation() *Location { return newLocation(1) } func callerLocation() *Location { return newLocation(2) } func newLocation(n int) *Location { if pc, _, _, ok := runtime.Caller(n +...
{ return this.name == that.name && this.file == that.file && this.line == that.line }
package sliceset import ( "sort" "github.com/xtgo/set" ) type Set []int func (s Set) Len() int { return len(s) } func (s Set) Less(i, j int) bool { return s[i] < s[j] } func (s Set) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s Set) Copy() Set { return append(Set(nil), s...) } func (s Set) U...
{ return s.DoBool(set.IsInter, t) }
package containers import ( "github.com/nanobox-io/golang-docker-client" "github.com/nanobox-io/nanobox/util/dhcp" ) func BridgeConfig() docker.ContainerConfig { return docker.ContainerConfig{ Name: BridgeName(), Image: "nanobox/bridge", Network: "virt", IP: reserveIP(),...
{ return "nanobox_bridge" }
package redis import ( "bytes" "encoding/gob" "github.com/iris-framework/iris/adaptors/sessions/sessiondb/redis/service" ) type Database struct { redis *service.Service } func New(cfg ...service.Config) *Database { return &Database{redis: service.New(cfg...)} } func (d *Database) Config() *service.Config {...
{ if len(newValues) == 0 { go d.redis.Delete(sid) } else { go d.redis.Set(sid, serialize(newValues)) } }
package jms import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type UpdateFleetAgentConfigurationRequest struct { FleetId *string `mandatory:"true" contributesTo:"path" name:"fleetId"` UpdateFleetAgentConfigurationDetails `contributesTo:"body"` IfMatch *string `mandatory:"false" contributesT...
{ return common.PointerString(response) }
package main import "fmt" var c chan int func main() { c := make(chan int) quit := make(chan bool) go count(c, quit) for i := 0; i < 10; i++ { c <- i } quit <- false } func count(c chan int, quit chan bool)
{ for { select { case i := <-c: fmt.Println(i) case <-quit: break } } }
package geom import "math" type Vertex struct { X, Y float64 } type Vertices []Vertex func (l Vertices) Convert() (data []float32) { data = make([]float32, len(l)*2) for i, v := range l { index := i * 2 data[index] = float32(v.X) data[index+1] = float32(v.Y) } return } func (c Vertex) SideOfLine(a ...
{ a[i], a[j] = a[j], a[i] }
package tango import ( "bytes" "net/http" "net/http/httptest" "testing" ) func TestDir1(t *testing.T) { buff := bytes.NewBufferString("") recorder := httptest.NewRecorder() recorder.Body = buff tg := New() tg.Get("/:name", Dir("./public")) req, err := http.NewRequest("GET", "http://localhost:8000/test.htm...
{ buff := bytes.NewBufferString("") recorder := httptest.NewRecorder() recorder.Body = buff tg := New() tg.Get("/test.html", File("./public/test.html")) req, err := http.NewRequest("GET", "http://localhost:8000/test.html", nil) if err != nil { t.Error(err) } tg.ServeHTTP(recorder, req) expect(t, recorder...
package addrs import "fmt" type ResourceInstancePhase struct { referenceable ResourceInstance ResourceInstance Phase ResourceInstancePhaseType } var _ Referenceable = ResourceInstancePhase{} func (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase { return Res...
{ return fmt.Sprintf("%s#%s", rp.Resource, rp.Phase) }
package cover import ( "flag" "io" "os" "strings" "testing" ) func ParseAndStripTestFlags() { flag.Parse() var runtimeArgs []string for _, arg := range os.Args { if strings.HasPrefix(arg, "-test.") || strings.HasPrefix(arg, "-httptest.") { continue } runtimeArgs = append(runtimeArgs, arg) } o...
{ return nil }
package client import ( "encoding/json" "fmt" ) type SystemSettings struct { userStreamAcl *StreamAcl systemStreamAcl *StreamAcl } func NewSystemSettings( userStreamAcl *StreamAcl, systemStreamAcl *StreamAcl, ) *SystemSettings { return &SystemSettings{userStreamAcl, systemStreamAcl} } func (s *SystemSettin...
{ return fmt.Sprintf("&{userStreamAcl:%+v systemStreamAcl:%+v}", s.userStreamAcl, s.systemStreamAcl) }
package service import ( log "github.com/golang/glog" "k8s.io/kubernetes/contrib/mesos/pkg/podutil" "k8s.io/kubernetes/contrib/mesos/pkg/scheduler/resources" "k8s.io/kubernetes/pkg/api" ) func StaticPodValidator( defaultContainerCPULimit resources.CPUShares, defaultContainerMemLimit resources.MegaBytes, acc...
{ return podutil.FilterFunc(func(pod *api.Pod) (bool, error) { _, cpu, _, err := resources.LimitPodCPU(pod, defaultContainerCPULimit) if err != nil { return false, err } _, mem, _, err := resources.LimitPodMem(pod, defaultContainerMemLimit) if err != nil { return false, err } log.V(2).Infof("rese...
package store import ( "bytes" "fmt" "reflect" "text/tabwriter" "time" ) type Metadata map[string]string type Entry struct { Name string `json:"name"` Password []byte `json:"password"` Ctime time.Time `json:"ctime"` Mtime time.Time `json:"mtime"` Metadata Metadata `json:"metadata"`...
{ var b bytes.Buffer for k, v := range m { fmt.Fprintf(&b, "%s:%s", k, v) } return b.String() }
package leet_25 type ListNode struct { Val int Next *ListNode } type dequeue struct { buff []*ListNode } func (q *dequeue) lpop() *ListNode { if 0 == len(q.buff) { return nil } p := q.buff[0] q.buff = q.buff[1:] return p } func (q *dequeue) rpop() *ListNode { if 0 == len(q.buff) { return nil } last ...
{ q.buff = buff[:0] }
package history import ( "fmt" "github.com/avatar29A/microchat/history/model" "github.com/avatar29A/microchat/server/protocols" "github.com/avatar29A/microchat/utils" log "github.com/Sirupsen/logrus" ) import "github.com/satori/go.uuid" type MessagesContext struct { ctx *DBContext } func NewMessagesContex...
{ channel := c.getDefaultChannel() entity := &model.Message{ ID: string(uuid.NewV4().Bytes()), UserName: message.Username, ChannelID: channel.ID, Message: message.Message, CreatedAt: utils.MakeTimeFromTimestamp(message.CreatedAt), } return c.ctx.DB.Save(entity) }
package migrator import ( "github.com/cgrates/cgrates/engine" "github.com/cgrates/cgrates/utils" ) func (m *Migrator) migrateCurrentTPactionplans() (err error) { tpids, err := m.storDBIn.StorDB().GetTpIds(utils.TBLTPActionPlans) if err != nil { return err } for _, tpid := range tpids { ids, err := m.storDBI...
{ var vrs engine.Versions current := engine.CurrentStorDBVersions() if vrs, err = m.getVersions(utils.TpActionPlans); err != nil { return } switch vrs[utils.TpActionPlans] { case current[utils.TpActionPlans]: if m.sameStorDB { break } if err := m.migrateCurrentTPactionplans(); err != nil { return er...
package sa import ( "fmt" "gopkg.in/go-gorp/gorp.v2" ) type RollbackError struct { Err error RollbackErr error } func Rollback(tx *gorp.Transaction, err error) error { if txErr := tx.Rollback(); txErr != nil { return &RollbackError{ Err: err, RollbackErr: txErr, } } return e...
{ if re.RollbackErr == nil { return re.Err.Error() } return fmt.Sprintf("%s (also, while rolling back: %s)", re.Err, re.RollbackErr) }
package dao import ( "context" "testing" "github.com/smartystreets/goconvey/convey" ) func TestDaoassetRelationKey(t *testing.T) { convey.Convey("assetRelationKey", t, func(ctx convey.C) { var ( mid = int64(0) ) ctx.Convey("When everything gose positive", func(ctx convey.C) { p1 := assetRelationKey(m...
{ convey.Convey("assetRelationField", t, func(ctx convey.C) { var ( oid = int64(0) otype = "" ) ctx.Convey("When everything gose positive", func(ctx convey.C) { p1 := assetRelationField(oid, otype) ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) { ctx.So(p1, convey.ShouldNotBeNil) ...
package sqltrace import ( "flag" "log" "os" "strconv" "sync/atomic" ) func boolToInt64(f bool) int64 { if f { return 1 } return 0 } type sqlTrace struct { on int64 *log.Logger } func newSQLTrace() *sqlTrace { return &sqlTrace{ Logger: log.New(os.Stdout, "hdb ", log.Ldate|log.Ltime|log.Lshortfile), ...
{ return atomic.LoadInt64(&t.on) != 0 }
package example1 import ( "fmt" ) type Runner interface { Run(string) (string, error) } type Gopher struct { name string age int } func (g Gopher) Run(desc string) (string, error)
{ return fmt.Sprintf("I am %s and I run for %s", g.name, desc), nil }
package league type Division struct { name string teams map[string]*Team confrence *Conference league *League } func (division *Division) GetName() string { return division.name } func (division *Division) GetConference() *Conference { return division.confrence } func (division *Division) getLea...
{ return division.teams }
package main import ( "fmt" "os" "os/exec" "github.com/rjeczalik/which" ) func die(v interface{}) { fmt.Fprintln(os.Stderr, v) os.Exit(1) } const usage = `NAME: gowhich - shows the import path of Go executables USAGE: gowhich name|path EXAMPLES: gowhich godoc gowhich ~/bin/godoc` func main() { if le...
{ return s == "-h" || s == "-help" || s == "help" || s == "--help" || s == "/?" }
package cachestore import ( "encoding/json" "sync" ) type CacheStore struct { stores map[string]*KVStore mutex sync.RWMutex } func (c *CacheStore) GetStore(svcName string) *KVStore { c.mutex.RLock() kvstore := c.stores[svcName] c.mutex.RUnlock() return kvstore } func (c *CacheStore) CreateStore(svcNa...
{ svcStore := c.GetStore(svcName) if svcStore == nil { svcStore = c.CreateStore(svcName) } svcStore.Set(key, value) }
package agent import ( "github.com/hashicorp/consul/consul/structs" "net/http" "sort" ) func coordinateDisabled(resp http.ResponseWriter, req *http.Request) (interface{}, error) { resp.WriteHeader(401) resp.Write([]byte("Coordinate support disabled")) return nil, nil } type sorter struct { coordinates str...
{ args := structs.DCSpecificRequest{} if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done { return nil, nil } var out structs.IndexedCoordinates defer setMeta(resp, &out.QueryMeta) if err := s.agent.RPC("Coordinate.ListNodes", &args, &out); err != nil { sort.Sort(&sorter{out.Coordinates...
package channelling import ( "bytes" "encoding/json" "errors" "log" "github.com/strukturag/spreed-webrtc/go/buffercache" ) type IncomingDecoder interface { DecodeIncoming(buffercache.Buffer) (*DataIncoming, error) } type OutgoingEncoder interface { EncodeOutgoing(*DataOutgoing) (buffercache.Buffer, error) } ...
{ return codec.buffers.New() }
package v1alpha1 import ( runtime "k8s.io/apimachinery/pkg/runtime" ) var _ runtime.NestedObjectDecoder = &AdmissionConfiguration{} var _ runtime.NestedObjectEncoder = &AdmissionConfiguration{} func (c *AdmissionConfiguration) EncodeNestedObjects(e runtime.Encoder) error { for k, v := range c.Plugins { if...
{ for k, v := range c.Plugins { decodeNestedRawExtensionOrUnknown(d, &v.Configuration) c.Plugins[k] = v } return nil }
package analyzer import ( . "github.com/levythu/gurgling" "time" "fmt" "strconv" ) type SimpleAnalyzer struct { } func ASimpleAnalyzer() Sandwich { return &SimpleAnalyzer{} } const token_returncode="SimpleAnalyzer-Status-Code" const token_starttime="SimpleAnalyzer-Start-Time" func (thi...
{ res.F()[token_returncode]=c }
package protobuf import "github.com/m3db/m3x/pool" const ( defaultInitBufferSize = 2880 defaultMaxUnaggregatedMessageSize = 50 * 1024 * 1024 ) type UnaggregatedOptions interface { SetBytesPool(value pool.BytesPool) UnaggregatedOptions BytesPool() pool.BytesPool SetInitBufferSize(value int) UnaggregatedOptio...
{ p := pool.NewBytesPool(nil, nil) p.Init() return &unaggregatedOptions{ bytesPool: p, initBufferSize: defaultInitBufferSize, maxMessageSize: defaultMaxUnaggregatedMessageSize, } }
package server import ( "net/http" "time" "aptweb" ) func NewServer(aptWebConfig *aptweb.Config, config *Config) *http.Server
{ h := NewHandler(aptWebConfig, config) s := &http.Server{ Addr: config.Address, Handler: h, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } return s }
package dom import ( "bytes" "fmt" ) type Node interface { String() string Parent() Node SetParent(node Node) Children() []Node AddChild(child Node) Clone() Node } type Element struct { text string parent Node children []Node } func NewElement(text string) *Element { return &Element{ text: ...
{ return e.children }
package app import ( "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" ) type AutoChannelCreator struct { client *model.Client team *model.Team Fuzzy bool DisplayNameLen utils.Range DisplayNameCharset string NameLen utils.Range ...
{ return &AutoChannelCreator{ client: client, team: team, Fuzzy: false, DisplayNameLen: CHANNEL_DISPLAY_NAME_LEN, DisplayNameCharset: utils.ALPHANUMERIC, NameLen: CHANNEL_NAME_LEN, NameCharset: utils.LOWERCASE, ChannelType: CHANNEL_TYP...
package rtda import ( "github.com/zxh0/jvm.go/rtda/heap" ) type FrameCache struct { thread *Thread cachedFrames []*Frame frameCount uint maxFrame uint } func newFrameCache(thread *Thread, maxFrame uint) *FrameCache { return &FrameCache{ thread: thread, maxFrame: maxFrame, cachedFram...
{ if cache.frameCount < cache.maxFrame { for i, cachedFrame := range cache.cachedFrames { if cachedFrame == nil { cache.cachedFrames[i] = frame cache.frameCount++ return } } } else { for _, cachedFrame := range cache.cachedFrames { if frame.maxLocals > cachedFrame.maxLocals { cachedFram...
package commands import ( log "github.com/sirupsen/logrus" "github.com/jamesread/ovress/pkg/indexer" "github.com/spf13/cobra" ) func runIndexCmd(cmd *cobra.Command, args []string) { for _, path := range args { log.WithFields(log.Fields{ "path": path, }).Infof("Indexing starting") root := indexer.Sca...
{ var indexCmd = &cobra.Command{ Use: "index", Short: "Indexes a file path", Run: runIndexCmd, Args: cobra.MinimumNArgs(1), } return indexCmd }
package unibyte import "unicode" func IsLower(b byte) bool { return b >= 'a' && b <= 'z' } func IsUpper(b byte) bool { return b >= 'A' && b <= 'Z' } func IsLetter(b byte) bool { return IsLower(b) || IsUpper(b) } func IsSpaceQuote(b byte) bool { return IsSpace(b) || b == '"' || b == '\'' } func ToLower...
{ return unicode.IsSpace(rune(b)) }
package aprs import ( "fmt" ) type PacketType byte var packetTypeNames = map[byte]string{ 0x1c: "Current Mic-E Data (Rev 0 beta)", 0x1d: "Old Mic-E Data (Rev 0 beta)", '!': "Position without timestamp (no APRS messaging), or Ultimeter 2000 WX Station", '#': "Peet Bros U-II Weather Station", '$': "Raw GPS d...
{ return p == ':' }
package atomic import ( "encoding/json" "strconv" "sync/atomic" ) type Uint32 struct { _ nocmp v uint32 } func NewUint32(val uint32) *Uint32 { return &Uint32{v: val} } func (i *Uint32) Load() uint32 { return atomic.LoadUint32(&i.v) } func (i *Uint32) Add(delta uint32) uint32 { return atomic.AddUint32...
{ v := i.Load() return strconv.FormatUint(uint64(v), 10) }
package payload import ( "fmt" "github.com/hyperledger/burrow/acm/acmstate" "github.com/hyperledger/burrow/crypto" ) func NewBondTx(address crypto.Address, amount uint64) *BondTx { return &BondTx{ Input: &TxInput{ Address: address, Amount: amount, }, } } func (tx *BondTx) Type() Type { return TypeB...
{ return fmt.Sprintf("BondTx{%v}", tx.Input) }
package vkutil import ( "strconv" "time" ) type EpochTime time.Time func (t EpochTime) MarshalJSON() ([]byte, error) { return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil } func (t EpochTime) ToTime() time.Time { return time.Time(t) } func (t *EpochTime) UnmarshalJSON(s []byte) error
{ var err error var q int64 if q, err = strconv.ParseInt(string(s), 10, 64); err != nil { return err } *(*time.Time)(t) = time.Unix(q, 0) return err }
package password import ( "crypto/rand" "encoding/base64" "time" jwt "github.com/dgrijalva/jwt-go" ) var signingKey = genRandBytes() func GenToken(id string) (string, error) { jwt := jwt.New(jwt.SigningMethodHS256) expTime := time.Now().Add(time.Hour * 72).Unix() jwt.Claims["sub"] = id jwt.Claims["exp"] =...
{ signingKey = key }
package aws import ( "log" "fmt" "github.com/hashicorp/terraform/helper/schema" ) func resourceAwsVpcPeeringConnectionAccepter() *schema.Resource { return &schema.Resource{ Create: resourceAwsVPCPeeringAccepterCreate, Read: resourceAwsVPCPeeringRead, Update: resourceAwsVPCPeeringUpdate, Delete: resour...
{ id := d.Get("vpc_peering_connection_id").(string) d.SetId(id) if err := resourceAwsVPCPeeringRead(d, meta); err != nil { return err } if d.Id() == "" { return fmt.Errorf("VPC Peering Connection %q not found", id) } return resourceAwsVPCPeeringUpdate(d, meta) }
package wire import ( "time" ) type periodicTask struct { period time.Duration task func() ticker *time.Ticker stop chan struct{} } func newPeriodicTask(period time.Duration, task func()) *periodicTask { return &periodicTask{ period: period, task: task, } } func (pt *periodicTask) Start() { if ...
{ for { select { case <-stop: return default: } select { case <-stop: return case <-ticker.C: pt.task() } } }
package embed import ( "fmt" "io/ioutil" "net/url" "os" "testing" "go.etcd.io/etcd/server/v3/auth" ) func TestStartEtcdWrongToken(t *testing.T) { tdir, err := ioutil.TempDir(os.TempDir(), "token-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tdir) cfg := NewConfig() urls := newEmbedURLs(2...
{ scheme := "unix" for i := 0; i < n; i++ { u, _ := url.Parse(fmt.Sprintf("%s:localhost:%d%06d", scheme, os.Getpid(), i)) urls = append(urls, *u) } return urls }
package main import ( "errors" "strings" "unicode" ) func splitQuoted(s string) (r []string, err error) { var args []string arg := make([]rune, len(s)) escaped := false quoted := false quote := '\x00' i := 0 for _, rune := range s { switch { case escaped: escaped = false case...
{ if i := strings.Index(s, sep); i >= 0 { return s[:i], s[i+len(sep):], true } return s, "", false }
package control import ( yaml "github.com/cloudfoundry-incubator/candiedyaml" "github.com/dansteen/controlled-compose/types" "github.com/docker/libcompose/config" "github.com/docker/libcompose/utils" "github.com/imdario/mergo.git" "io/ioutil" "path/filepath" ) func processRequires(file string, configFiles [...
{ var configContent config.Config var mergedConfig config.Config for _, file := range files { content, err := ioutil.ReadFile(file) if err != nil { return nil, err } err = yaml.Unmarshal(content, &configContent) if err != nil { return nil, err } err = mergo.Merge(&mergedConfig, configContent) ...
package container type ( Lifo struct { Fifo } ) func (li *Lifo) Less(i, j int) bool
{ return li.data[i].index > li.data[j].index }
package algorithms import "log" func canCompleteCircuit(gas []int, cost []int) int { for i := 0; i < len(gas); i++ { gas[i] = gas[i] - cost[i] } log.Println("A:", gas) index := 0 for i := 1; i < len(gas); i++ { gas[i] += gas[i-1] if gas[i] < gas[index] { index = i } } log.Println("B:", gas) if ga...
{ index := 0 for i := 0; i < len(gas); i++ { gas[i] = gas[i] - cost[i] if i > 0 { gas[i] += gas[i-1] if gas[i] < gas[index] { index = i } } } if gas[len(gas)-1] < 0 { return -1 } return (index + 1) % len(gas) }
package zk import "github.com/go-kit/kit/log" type Registrar struct { client Client service Service logger log.Logger } type Service struct { Path string Name string Data []byte node string } func (r *Registrar) Register() { if err := r.client.Register(&r.service); err != nil { r.logger.Log(...
{ return &Registrar{ client: client, service: service, logger: log.With(logger, "service", service.Name, "path", service.Path, "data", string(service.Data), ), } }
package kv_test import ( "context" "testing" "github.com/influxdata/influxdb" "github.com/influxdata/influxdb/kv" influxdbtesting "github.com/influxdata/influxdb/testing" ) func TestBoltOrganizationService(t *testing.T) { influxdbtesting.OrganizationService(initBoltOrganizationService, t) } func TestInmemOrga...
{ svc := kv.NewService(s) svc.OrgBucketIDs = f.OrgBucketIDs svc.IDGenerator = f.IDGenerator svc.TimeGenerator = f.TimeGenerator if f.TimeGenerator == nil { svc.TimeGenerator = influxdb.RealTimeGenerator{} } ctx := context.Background() if err := svc.Initialize(ctx); err != nil { t.Fatalf("error initializing...
package service import ( "net/http" "github.com/go-openapi/runtime" "github.com/cilium/cilium/api/v1/models" ) const GetServiceIDOKCode int = 200 type GetServiceIDOK struct { Payload *models.Service `json:"body,omitempty"` } func NewGetServiceIDOK() *GetServiceIDOK { return &GetServiceIDOK{} } func...
{ return &GetServiceIDNotFound{} }
package alicloud type PrimaryKeyTypeString string const ( IntegerType = PrimaryKeyTypeString("Integer") StringType = PrimaryKeyTypeString("String") BinaryType = PrimaryKeyTypeString("Binary") ) type InstanceAccessedByType string const ( AnyNetwork = InstanceAccessedByType("Any") VpcOnly = InstanceAcce...
{ switch instanceType { case "SSD": return OtsHighPerformance default: return OtsCapacity } }
package assert func isPrime(value int) bool
{ if value <= 3 { return value >= 2 } if value%2 == 0 || value%3 == 0 { return false } uns := uint(value) for i := uint(5); i*i <= uns; i += 6 { if uns%i == 0 || uns%(i+2) == 0 { return false } } return true }
package state import ( "net/url" "gopkg.in/juju/charm.v3" ) type charmDoc struct { URL *charm.URL `bson:"_id"` Meta *charm.Meta Config *charm.Config Actions *charm.Actions BundleURL *url.URL BundleSha256 string PendingUpload bool Placeholder bool } type Charm struc...
{ return c.doc.Config }
package emperror import ( "errors" "fmt" ) func Recover(r interface{}) (err error)
{ if r != nil { switch x := r.(type) { case string: err = errors.New(x) case error: err = x default: err = fmt.Errorf("unknown panic, received: %v", r) } if _, ok := StackTrace(err); !ok { err = &wrappedError{ err: err, stack: callers()[2:], } } } return err }
package systemd import ( "fmt" "strings" "github.com/google/cadvisor/container" "github.com/google/cadvisor/fs" info "github.com/google/cadvisor/info/v1" "github.com/google/cadvisor/watcher" "k8s.io/klog/v2" ) type systemdFactory struct{} func (f *systemdFactory) String() string { return "systemd" } func ...
{ if strings.HasSuffix(name, ".mount") { return true, false, nil } klog.V(5).Infof("%s not handled by systemd handler", name) return false, false, nil }
package errors func NewEmptyResourceError() *EmptyResourceError { return &EmptyResourceError{} } type EmptyResourceError struct{} func (e *EmptyResourceError) Error() string
{ return "EmptyResourceError" }
package wifi var _ = WiFi(&StubWorker{}) type StubWorker struct { Options []Option ID string } func (w *StubWorker) Scan() ([]Option, error) { return w.Options, nil } func (*StubWorker) Connect(a ...string) error { return nil } func NewStubWorker(id string, options ...Option) (WiFi, error) { return &St...
{ return w.ID, nil }
package caaa import ( "encoding/xml" "github.com/fgrid/iso20022" ) type Document00900101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.01 Document"` Message *AcceptorReconciliationRequestV01 `xml:"AccptrRcncltnReq"` } func (d *Document00900101) AddMessage()...
{ a.Header = new(iso20022.Header1) return a.Header }
package main import ( "syscall" ) func setRlimit() error
{ rlimit := int64(100000) if rlimit > 0 { var limit syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { return err } if limit.Cur < rlimit { limit.Cur = rlimit if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { return err } } } retu...
package credentials import ( "strings" "github.com/docker/docker/cliconfig/configfile" "github.com/docker/engine-api/types" ) type fileStore struct { file *configfile.ConfigFile } func NewFileStore(file *configfile.ConfigFile) Store { return &fileStore{ file: file, } } func (c *fileStore) Erase(serverA...
{ c.file.AuthConfigs[authConfig.ServerAddress] = authConfig return c.file.Save() }
package aggregator import ( "github.com/CapillarySoftware/gostat/stat" "math" ) func Aggregate(stats []*stat.Stat) (aggregate StatsAggregate) { if stats == nil || len(stats) == 0 { return StatsAggregate{} } aggregate = StatsAggregate{Min : stats[0].Value, Max : stats[0].Value, Count : len(stats)} sum := 0....
{ if (a.Count == 0) { return b } if (b.Count == 0) { return a } aggregate.Average = ( (a.Average * float64(a.Count)) + (b.Average * float64(b.Count)) ) / float64(a.Count + b.Count) aggregate.Min = math.Min(a.Min, b.Min) aggregate.Max = math.Max(a.Max, b.Max) aggregate.Count = a.Count + b.Count ...
package contextutil_test import ( "errors" "testing" "time" "github.com/arjantop/cuirass/util/contextutil" "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) func TestDoWithCancelErrorReturned(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := cont...
{ ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := contextutil.Do(ctx, func() error { return errors.New("foo") }) assert.Equal(t, errors.New("foo"), err) }
package bits_test import ( "github.com/twmb/bits" "testing" ) func TestSet(t *testing.T) { for i := 0; i < 256; i++ { if int(bits.SetU32(uint32(i))) != bits.Hamming(i, 0) { t.Errorf("Error in set: wanted %v for %v, got %v", bits.Hamming(i, 0), i, bits.SetU32(uint32(i))) } } } func BenchmarkSetKernigh...
{ for i := 0; i < b.N; i++ { bits.SetTable(i) } }
package main import ( "log" "os" "os/signal" "syscall" "github.com/opensourceorg/api/license" ) type Blobs struct { Licenses license.Licenses LicenseIdMap map[string]license.License LicenseTagMap map[string][]license.License } func loadBlob(path string, blob *Blobs) error { licenses, err := license.L...
{ if err := loadBlob(file, target); err != nil { panic(err) } c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) for _ = range c { if err := loadBlob(file, target); err != nil { log.Printf("Error! Can not reload the JSON! - %s", err) continue } } }
package iso20022 type ATMTransactionAmounts6 struct { Currency *ActiveCurrencyCode `xml:"Ccy,omitempty"` MaximumPossibleAmount *ImpliedCurrencyAndAmount `xml:"MaxPssblAmt,omitempty"` MinimumPossibleAmount *ImpliedCurrencyAndAmount `xml:"MinPssblAmt,omitempty"` AdditionalAmount []*ATMTransactionAmounts7 `xml:"...
{ a.Currency = (*ActiveCurrencyCode)(&value) }
package systray import "C" import ( "unsafe" ) func nativeLoop() { C.nativeLoop() } func quit() { C.quit() } func SetIcon(iconBytes []byte) { cstr := (*C.char)(unsafe.Pointer(&iconBytes[0])) C.setIcon(cstr, (C.int)(len(iconBytes))) } func SetTitle(title string) { C.setTitle(C.CString(title)) } func ...
{ var disabled C.short = 0 if item.disabled { disabled = 1 } var checked C.short = 0 if item.checked { checked = 1 } C.add_or_update_menu_item( C.int(item.id), C.CString(item.title), C.CString(item.tooltip), disabled, checked, ) }
package displayers import ( "fmt" "io" "github.com/digitalocean/doctl/do" ) type Size struct { Sizes do.Sizes } var _ Displayable = &Size{} func (si *Size) JSON(out io.Writer) error { return writeJSON(si.Sizes, out) } func (si *Size) ColMap() map[string]string { return map[string]string{ "Slug": "Slug",...
{ return []string{ "Slug", "Memory", "VCPUs", "Disk", "PriceMonthly", "PriceHourly", } }
package build import "github.com/docker/docker/api/server/router" type buildRouter struct { backend Backend routes []router.Route } func NewRouter(b Backend) router.Router { r := &buildRouter{ backend: b, } r.initRoutes() return r } func (r *buildRouter) initRoutes() { r.routes = []router.Route{ ro...
{ return r.routes }
package migrations import ( "database/sql" "github.com/pressly/goose" ) func init() { goose.AddMigration(up00002, down00002) } func down00002(tx *sql.Tx) error { _, err := tx.Exec(`DROP TABLE users`) return err } func up00002(tx *sql.Tx) error
{ _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS users (email text)`) return err }
package internal import ( "fmt" "net/http" "golang.org/x/net/context" ) type ContextKey string const userAgent = "gcloud-golang/0.1" type Transport struct { Base http.RoundTripper } func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { req = cloneRequest(req) ua := req.Header.Get...
{ v := ctx.Value(ContextKey("namespace")) if v == nil { return "" } else { return v.(string) } }
package app import ( "net/url" ) type Service interface { ProxyPath() string URL() string BasicAuth() (username, password string, ok bool) AddSecret(parameters url.Values) } type basicAuthService struct { proxyPath, url, clientId, clientSecret string } func (s basicAuthService) ProxyPath() string { return s....
{ return s.url }
package iso20022 type PlainCardData4 struct { PAN *Min8Max28NumericText `xml:"PAN"` CardSequenceNumber *Min2Max3NumericText `xml:"CardSeqNb,omitempty"` EffectiveDate *Max10Text `xml:"FctvDt,omitempty"` ExpiryDate *Max10Text `xml:"XpryDt"` ServiceCode *Exact3NumericText `xml:"SvcCd,omitempty"` TrackData []...
{ p.CardSequenceNumber = (*Min2Max3NumericText)(&value) }
package geth import ( "errors" "fmt" ) type Strings struct{ strs []string } func (s *Strings) Size() int { return len(s.strs) } func (s *Strings) Get(index int) (str string, _ error) { if index < 0 || index >= len(s.strs) { return "", errors.New("index out of bounds") } return s.strs[index], nil } func...
{ return fmt.Sprintf("%v", s.strs) }
package ergo_test import ( "fmt" "testing" "github.com/gima/ergo/v1" "github.com/gima/ergo/v1/pp" "github.com/stretchr/testify/require" ) func TestComposer_AddLinked(t *testing.T) { olde := fmt.Errorf("") oldE := ergo.New("").Err() E := ergo.New("").AddLinked(olde, oldE).Err() require.Equal(t, 2, E.Li...
{ E := ergo.New("").Err() require.Equal(t, 0, E.Context().Len()) E = ergo.New("").AddContext("K1", "V1").Err() require.Equal(t, 1, E.Context().Len()) k, v := E.Context().Get(0) require.Equal(t, "K1V1", k+v) E = ergo.New("").AddContextFrom(pp.Map{"K1": "V1"}).Err() require.Equal(t, 1, E.Context().Len()) k, v ...
package log15 import ( "sync/atomic" "unsafe" ) type swapHandler struct { handler unsafe.Pointer } func (h *swapHandler) Log(r *Record) error { return (*(*Handler)(atomic.LoadPointer(&h.handler))).Log(r) } func (h *swapHandler) Swap(newHandler Handler)
{ atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) }
package types import ( "math" ) func RoundFloat(val float64) float64 { v, frac := math.Modf(val) if val >= 0.0 { if frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) { v += 1.0 } } else { if frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) { v -= 1.0 } } return v } func getMaxFloat(flen int, ...
{ pow := math.Pow10(decimal) t := (f - math.Floor(f)) * pow round := RoundFloat(t) f = math.Floor(f) + round/pow return f }
package hook import ( "fmt" "gopkg.in/juju/charm.v6-unstable/hooks" "gopkg.in/juju/names.v2" ) const ( LeaderElected hooks.Kind = "leader-elected" LeaderDeposed hooks.Kind = "leader-deposed" LeaderSettingsChanged hooks.Kind = "leader-settings-changed" ) type Info struct { Kind hooks.Kind `...
{ switch hi.Kind { case hooks.RelationJoined, hooks.RelationChanged, hooks.RelationDeparted: if hi.RemoteUnit == "" { return fmt.Errorf("%q hook requires a remote unit", hi.Kind) } fallthrough case hooks.Install, hooks.Start, hooks.ConfigChanged, hooks.UpgradeCharm, hooks.Stop, hooks.RelationBroken, hooks...
package core import ( "github.com/google/blueprint" ) type generateBinary struct { generateLibrary } var _ generateLibraryInterface = (*generateBinary)(nil) var _ singleOutputModule = (*generateBinary)(nil) var _ splittable = (*generateBinary)(nil) var _ blueprint.Module = (*generateBinary)(nil) func (m *generat...
{ return "" }
package version import ( "bytes" "fmt" ) var ( GitCommit string Version = "0.13.0" VersionPrerelease = "dev" VersionMetadata = "" ) type VersionInfo struct { Revision string Version string VersionPrerelease string VersionMetadata string } func (c *VersionInfo) VersionNumber(re...
{ ver := Version rel := VersionPrerelease md := VersionMetadata return &VersionInfo{ Revision: GitCommit, Version: ver, VersionPrerelease: rel, VersionMetadata: md, } }
package iso20022 type PaymentTransaction17 struct { SettlementAmount *ActiveCurrencyAndAmount `xml:"SttlmAmt,omitempty"` SettlementDate *ISODate `xml:"SttlmDt,omitempty"` PaymentInstrument *PaymentInstrument9Choice `xml:"PmtInstrm,omitempty"` } func (p *PaymentTransaction17) SetSettlementDate(value string) {...
{ p.SettlementAmount = NewActiveCurrencyAndAmount(value, currency) }
package runconfig import ( "fmt" "strings" ) func validateNetMode(vals *validateNM) error { if (vals.netMode.IsHost() || vals.netMode.IsContainer()) && *vals.flHostname != "" { return ErrConflictNetworkHostname } if vals.netMode.IsHost() && vals.flLinks.Len() > 0 { return ErrConflictHostNetworkAndLinks ...
{ parts := strings.Split(netMode, ":") switch mode := parts[0]; mode { case "default", "bridge", "none", "host": case "container": if len(parts) < 2 || parts[1] == "" { return "", fmt.Errorf("invalid container format container:<name|id>") } default: return "", fmt.Errorf("invalid --net: %s", netMode) } ...
package cronjob import ( context "context" v1beta1 "k8s.io/client-go/informers/batch/v1beta1" factory "knative.dev/pkg/client/injection/kube/informers/factory" controller "knative.dev/pkg/controller" injection "knative.dev/pkg/injection" logging "knative.dev/pkg/logging" ) func init() { injection.Default.Regi...
{ f := factory.Get(ctx) inf := f.Batch().V1beta1().CronJobs() return context.WithValue(ctx, Key{}, inf), inf.Informer() }
package associations_test import ( "reflect" "testing" "github.com/gobuffalo/pop/associations" "github.com/gobuffalo/pop/nulls" "github.com/stretchr/testify/require" ) type FooHasMany struct { ID int `db:"id"` BarHasManies *barHasManies `has_many:"bar_has_manies"` } type barHasMany struct...
{ a := require.New(t) id := 1 foo := FooHasMany{ID: 1} as, err := associations.ForStruct(&foo) a.NoError(err) a.Equal(len(as), 1) a.Equal(reflect.Slice, as[0].Kind()) where, args := as[0].Constraint() a.Equal("foo_has_many_id = ?", where) a.Equal(id, args[0].(int)) }
package auth import ( "context" ) type tokenNop struct{} func (t *tokenNop) enable() {} func (t *tokenNop) disable() {} func (t *tokenNop) invalidateUser(string) {} func (t *tokenNop) genTokenPrefix() (string, error) { return "", nil } func (t *tokenNop) ass...
{ return nil, false }
package validate import ( "io/ioutil" "os" "sync" "testing" "github.com/stretchr/testify/assert" ) var ( logMutex = &sync.Mutex{} ) func TestDebug(t *testing.T)
{ if !enableLongTests { skipNotify(t) t.SkipNow() } tmpFile, _ := ioutil.TempFile("", "debug-test") tmpName := tmpFile.Name() defer func() { Debug = false logMutex.Unlock() os.Remove(tmpName) }() logMutex.Lock() Debug = true debugOptions() defer func() { validateLogger.SetOutput(os.Stdout) }() ...
package spatial import "fmt" func (p Polygon) string() string { s := "(" for _, line := range p { s += fmt.Sprintf("%v, ", line) } return s[:len(s)-2] + ")" } func (l Line) string() string
{ s := "" for _, point := range l { s += fmt.Sprintf("%v, ", point) } return s[:len(s)-2] }
package application import ( "encoding/base64" "github.com/gorilla/securecookie" "net/http" "testing" ) const cookieName = "recaptcha" const testHashKey = "RovMQmutMbSogUuGQFZYLb37jwgwFNuMR7wrEz9EILQ9W039UHCFlCfkpX1EbecktHA563XX+7clPRinBPeaeQ==" const testBlockKey = "+sSXCAbwswiYNqHx4zCuJJTD3hmRQp4f4uJKy+aFL70="...
{ validCookie := &http.Cookie{Value: "Some Value"} secureRecaptchaCookie := NewSecureRecaptchaCookie(cookieName, validCookie, generateGorillaSecureCookie()) secureRecaptchaCookie.Value = secureRecaptchaCookie.Encode(validCookie.Value) if secureRecaptchaCookie.IsValid(validCookie.Value) != true { t.Error("The co...
End of preview. Expand in Data Studio

max_src_len = 512, max_trg_len = 256

Downloads last month
13