input
stringlengths
24
2.11k
output
stringlengths
7
948
package stick import ( "encoding/json" "fmt" "reflect" "strings" "go.mongodb.org/mongo-driver/bson" ) type Coding string const ( JSON Coding = "json" BSON Coding = "bson" ) func (c Coding) Marshal(in interface{}) ([]byte, error) { switch c { case JSON: return json.Marshal(in) case BSON: return bso...
{ switch c { case JSON: return json.Unmarshal(in, out) case BSON: return bson.Unmarshal(in, out) default: panic(fmt.Sprintf("coal: unknown coding %q", c)) } }
package main import ( "github.com/stretchr/testify/assert" "github.com/xtracdev/xavi/env" "github.com/xtracdev/xavi/plugin" "os" "testing" ) func TestPluginRegistration(t *testing.T) { registerPlugins() assert.True(t, plugin.RegistryContains("Logging")) } func TestXapHook(t *testing.T) { os.Setenv(env.Loggin...
{ grabCommandLineArgs() }
package cron import ( "fmt" "github.com/Cepave/agent/g" "github.com/Cepave/common/model" "log" "time" ) func reportAgentStatus(interval time.Duration) { for { hostname, err := g.Hostname() if err != nil { hostname = fmt.Sprintf("error:%s", err.Error()) } req := model.AgentReportRequest{ Hostnam...
{ if g.Config().Heartbeat.Enabled && g.Config().Heartbeat.Addr != "" { go reportAgentStatus(time.Duration(g.Config().Heartbeat.Interval) * time.Second) } }
package elements_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/purl.org/dc/elements" ) func TestSimpleLiteralMarshalUnmarshal(t *testing.T) { v := elements.NewSimpleLiteral() buf, _ := xml.Marshal(v) v2 := elements.NewSimpleLiteral() xml.Unmarshal(buf, v2) } func TestSimpleLiteralConst...
{ v := elements.NewSimpleLiteral() if v == nil { t.Errorf("elements.NewSimpleLiteral must return a non-nil value") } if err := v.Validate(); err != nil { t.Errorf("newly constructed elements.SimpleLiteral should validate: %s", err) } }
package network import ( "github.com/docker/docker/api/server/httputils" "github.com/docker/docker/api/server/router" ) type networkRouter struct { routes []router.Route } type networkRoute struct { path string handler httputils.APIFunc } func (l networkRoute) Handler() httputils.APIFunc { return l.ha...
{ return n.routes }
package main import ( "github.com/pebbe/zmq4/examples/mdapi" "errors" "fmt" "os" "time" ) func main() { var verbose bool if len(os.Args) > 1 && os.Args[1] == "-v" { verbose = true } session, _ := mdapi.NewMdcli("tcp:localhost:5555", verbose) reply, err := ServiceCall(session, "titanic.request", "...
{ reply = []string{} msg, err := session.Send(service, request...) if err == nil { switch status := msg[0]; status { case "200": reply = msg[1:] return case "400": fmt.Println("E: client fatal error, aborting") os.Exit(1) case "500": fmt.Println("E: server fatal error, aborting") os.Exit(1)...
package kms import ( "os" "github.com/denverdino/aliyungo/common" ) const ( KMSDefaultEndpoint = "https://kms.cn-hangzhou.aliyuncs.com" KMSAPIVersion = "2016-01-20" KMSServiceCode = "kms" ) type Client struct { common.Client } func NewClient(accessKeyId, accessKeySecret string) *Client { endpoint ...
{ endpoint := os.Getenv("KMS_ENDPOINT") if endpoint == "" { endpoint = KMSDefaultEndpoint } return NewKMSClientWithEndpointAndSecurityToken(endpoint, accessKeyId, accessKeySecret, securityToken, regionID) }
package main import ( "bytes" "github.com/bitly/go-nsq" ) type BackendQueue interface { Put([]byte) error ReadChan() chan []byte Close() error Delete() error Depth() int64 Empty() error } type DummyBackendQueue struct { readChan chan []byte } func (d *DummyBackendQueue) Put([]byte) error { return ni...
{ return &DummyBackendQueue{readChan: make(chan []byte)} }
package storage import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" genericapirequest "k8s.io/apiserver/pkg/request" "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/genericapiserver/api/rest" "k8s.io/kubernetes/pkg/registry/batch/job" "k8s.io/kubernetes/pkg/registr...
{ store := &genericregistry.Store{ NewFunc: func() runtime.Object { return &batch.Job{} }, NewListFunc: func() runtime.Object { return &batch.JobList{} }, ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*batch.Job).Name, nil }, PredicateFunc: job.MatchJob, QualifiedResourc...
package client import ( "math" "math/rand" "time" "github.com/paybyphone/kintail/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request" ) type DefaultRetryer struct { NumMaxRetries int } func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { delay := int(math.Pow(2, floa...
{ return d.NumMaxRetries }
package vault import ( "fmt" "strings" ) type AuthType interface { Describe() string GetType() string getAuthConfig() map[string]interface{} getAuthMountConfig() map[string]interface{} Configure(c *VCClient) error TuneMount(c *VCClient, path string) error WriteUsers(c *VCClient) error WriteGroups(c *VCClie...
{ if err := c.Sys().EnableAuth(a.GetType(), a.GetType(), a.Describe()); err != nil { return err } return nil }
package nodes import "bufio" type Representation struct { Content string `bson:"c"` } func (r *Representation) Render(w *bufio.Writer) error
{ w.WriteString(r.Content) return nil }
package cluster_health import ( "fmt" "os" "testing" mbtest "github.com/elastic/beats/metricbeat/mb/testing" ) func TestData(t *testing.T) { f := mbtest.NewEventFetcher(t, getConfig()) err := mbtest.WriteEvent(f, t) if err != nil { t.Fatal("write", err) } } const ( cephDefaultHost = "127.0.0.1" cephDe...
{ return map[string]interface{}{ "module": "ceph", "metricsets": []string{"cluster_health"}, "hosts": getTestCephHost(), } }
package operations import ( "github.com/denkhaus/bitshares/types" "github.com/denkhaus/bitshares/util" "github.com/juju/errors" ) func init() { types.OperationMap[types.OperationTypeTransferFromBlind] = func() types.Operation { op := &TransferFromBlindOperation{} return op } } type TransferFromBlindOperat...
{ return types.OperationTypeTransferFromBlind }
package github import ( "strconv" "time" ) type Timestamp struct { time.Time } func (t *Timestamp) UnmarshalJSON(data []byte) (err error) { str := string(data) i, err := strconv.ParseInt(str, 10, 64) if err == nil { t.Time = time.Unix(i, 0) } else { t.Time, err = time.Parse(`"`+time.RFC3339+`"`, s...
{ return t.Time.String() }
package v1 import ( v1 "github.com/openshift/api/config/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) type IdentityProviderLister interface { List(selector labels.Selector) (ret []*v1.IdentityProvider, err error) Get(name string) (*v1.IdentityProvide...
{ return &identityProviderLister{indexer: indexer} }
package cgo import ( "testing" ) func TestRead(t *testing.T) { testRead(t) } func TestWrite(t *testing.T)
{ testWrite(t) }
package v1beta3 import ( "github.com/GoogleCloudPlatform/kubernetes/pkg/api" ) func init()
{ api.Scheme.AddKnownTypes("v1beta3", &User{}, &UserList{}, &Identity{}, &IdentityList{}, &UserIdentityMapping{}, ) }
package log type logLevel struct { Level int Prefix string ColorFunc func(...interface{}) string } type logLevels []*logLevel func (l *logLevels) getLevel(Level int) *logLevel { for _, item := range *l { if item.Level == Level { return item } } return nil } func (l *logLevels) getFunc(Level in...
{ level := l.getLevel(Level) if level != nil { return level.ColorFunc } return nil }
package main import ( "strings" "github.com/n0rad/go-erlog/errs" ) type envMap struct { mapping map[string]string } func (e *envMap) Set(s string) error { if e.mapping == nil { e.mapping = make(map[string]string) } pair := strings.SplitN(s, "=", 2) if len(pair) != 2 { return errs.With("environment variab...
{ return strings.Join(e.Strings(), "\n") }
package types import ( "fmt" "testing" "gopkg.in/yaml.v1" "github.com/stretchr/testify/assert" ) func newLocalDevicesObj() *LocalDevices { return &LocalDevices{ Driver: "vfs", DeviceMap: map[string]string{ "vfs-000": "/dev/xvda", "vfs-001": "/dev/xvdb", "vfs-002": "/dev/xvdc", }, } } var expec...
{ ld1 := newLocalDevicesObj() assert.Equal(t, expectedLD1String, ld1.String()) t.Logf("localDevices=%s", ld1) ld2 := &LocalDevices{} assert.NoError(t, ld2.UnmarshalText([]byte(ld1.String()))) assert.EqualValues(t, ld1, ld2) }
package common import ( "fmt" "os" "runtime" "runtime/debug" "strings" ) func Report(extra ...interface{}) { fmt.Fprintln(os.Stderr, "You've encountered a sought after, hard to reproduce bug. Please report this to the developers <3 https:github.com/WhaleCoinOrg/WhaleCoin/issues") fmt.Fprintln(os.Stderr, extra...
{ line := strings.Repeat("#", len(str)+4) emptyLine := strings.Repeat(" ", len(str)) fmt.Printf(` %s # %s # # %s # # %s # %s `, line, emptyLine, str, emptyLine, line) }
package job import ( "context" "github.com/google/gapid/core/data/search" "github.com/google/gapid/core/event" "github.com/google/gapid/core/net/grpcutil" "github.com/google/gapid/core/os/device" "google.golang.org/grpc" ) type remote struct { client ServiceClient } func NewRemote(ctx context.Context, conn ...
{ stream, err := m.client.SearchWorkers(ctx, query) if err != nil { return err } return event.Feed(ctx, event.AsHandler(ctx, handler), grpcutil.ToProducer(stream)) }
package bunyan import "os" type Sink interface { Write(record Record) error } type funcSink struct { write func(record Record) error } func (sink *funcSink) Write(record Record) error { return sink.write(record) } func SinkFunc(write func(record Record) error) Sink { return &funcSink{write} } func Inf...
{ return SinkFunc(func(record Record) error { return nil }) }
package model import ( "fmt" native_time "time" ) type Timestamp int64 const ( MinimumTick = native_time.Second second = int64(native_time.Second / MinimumTick) ) func (t Timestamp) Equal(o Timestamp) bool { return t == o } func (t Timestamp) Before(o Timestamp) bool { return t < o } func (t Times...
{ return Timestamp(t * second) }
package databasemigration import ( "github.com/oracle/oci-go-sdk/v46/common" ) type WorkRequestErrorCollection struct { Items []WorkRequestError `mandatory:"true" json:"items"` } func (m WorkRequestErrorCollection) String() string
{ return common.PointerString(m) }
package s2 var ( _ Shape = (*PointVector)(nil) ) type PointVector []Point func (p *PointVector) NumEdges() int { return len(*p) } func (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} } func (p *PointVector) ReferencePoint() ReferencePoint { return O...
{ return typeTagPointVector }
package wire import ( "bytes" "io" ) type fixedWriter struct { b []byte pos int } func (w *fixedWriter) Write(p []byte) (n int, err error) { lenp := len(p) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } n = lenp w.pos += copy(w.b[w.pos:], p) return } func (w *fixedWriter) Bytes() []by...
{ b := make([]byte, max) if buf != nil { copy(b, buf) } iobuf := bytes.NewBuffer(b) fr := fixedReader{b, 0, iobuf} return &fr }
package coap import ( "encoding/binary" "errors" "io" ) type TcpMessage struct { Message } func (m *TcpMessage) UnmarshalBinary(data []byte) error { if len(data) < 4 { return errors.New("short packet") } return m.Message.UnmarshalBinary(data) } func Decode(r io.Reader) (*TcpMessage, error) { var ln ...
{ bin, err := m.Message.MarshalBinary() if err != nil { return nil, err } l := []byte{0, 0} binary.BigEndian.PutUint16(l, uint16(len(bin))) return append(l, bin...), nil }
package constraint import ( "fmt" "github.com/hashicorp/go-multierror" ) type ExactlyOne struct { Constraints []Check } var _ Range = &ExactlyOne{} func (e *ExactlyOne) ValidateItems(arr []interface{}, p Params) error
{ var matches int var err error mainloop: for _, a := range arr { for _, c := range e.Constraints { er := c.ValidateItem(a, p) if er != nil { err = multierror.Append(err, er) continue mainloop } } matches++ } switch matches { case 0: err = multierror.Append(err, fmt.Errorf("no item match...
package colorable import ( "io" "os" ) func NewColorableStdout() io.Writer { return os.Stdout } func NewColorableStderr() io.Writer { return os.Stderr } func NewColorable(file *os.File) io.Writer
{ if file == nil { panic("nil passed instead of *os.File to NewColorable()") } return file }
package s3storage import ( "testing" "github.com/AdRoll/goamz/aws" "github.com/AdRoll/goamz/s3" "github.com/AdRoll/goamz/s3/s3test" "github.com/facebookgo/ensure" ) type MockS3 struct { auth aws.Auth region aws.Region srv *s3test.Server config *s3test.Config } func (s *MockS3) Start(t *testing.T) { ...
{ return NewS3Storage(s.region, s.auth, "testbucket", "test", s3.Private) }
package rorm type rorm struct { redisQuerier *RedisQuerier } func NewROrm() ROrmer { return new(rorm).Using("default") } func (r *rorm) QueryHash(key string) HashQuerySeter { return &hashQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryKeys(key string) KeysQuerySeter { re...
{ return r.redisQuerier }
package main import ("log"; "net") func main() { ln, err := net.Listen("tcp", ":6000") if err != nil { log.Fatal(err) } for { conn, err := ln.Accept() if err != nil { log.Println(err) continue } go handleConnection(conn) } } func h...
{ buf := make([]byte, 4096) for { n, err := c.Read(buf) if err != nil || n == 0 { c.Close() break } n, err = c.Write(buf[0:n]) if err != nil { c.Close() break } } log.Printf("Connection from %v closed.", c.R...
package cacheval import ( "math/rand" "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func TestInt32Stress(t *testing.T) { const valid = 10 * time.Millisecond const delay = 1 * time.Millisecond const concurrency = 50 const N = 500 cv := Int32{} cv.Init(valid) wg := sync.WaitGroup{} wg...
{ t.Parallel() rand := rand.New(rand.NewSource(time.Now().UnixNano())) const valid = 100 * time.Millisecond cv := Int32{} cv.Init(valid) assert.Equal(t, int32(0), cv.Get()) v, ok := cv.GetFresh() assert.Equal(t, int32(0), v) assert.Equal(t, false, ok) expect := int32(rand.Uint32()) cv.Set(expect) v, ok ...
package toJson import ( "encoding/json" "fmt" "net/http" ) func WriteToJson(w http.ResponseWriter, obj interface{}) error { return WriteToJsonWithCode(w, obj, http.StatusOK) } func WriteToJsonWithCode(w http.ResponseWriter, obj interface{}, code int) error { o, err := ToJson(obj) if err != nil { writeError(e...
{ return WriteToJsonNotWrappedWithCode(w, obj, http.StatusOK) }
package client import ( atlantis "atlantis/common" . "atlantis/manager/constant" ) type ManagerRPCClient struct { atlantis.RPCClient User string Secrets map[string]string } type AuthedArg interface { SetCredentials(string, string) } func (r *ManagerRPCClient) CallAuthed(name string, arg AuthedArg, reply in...
{ return atlantis.NewMultiRPCClientWithConfig(cfg, "ManagerRPC", ManagerRPCVersion, true) }
package retry import ( "context" "k8s.io/apimachinery/pkg/util/wait" ) type ConditionWithContextFunc func(ctx context.Context) (done bool, err error) func ExponentialBackoffWithContext(ctx context.Context, backoff wait.Backoff, condition ConditionWithContextFunc) error
{ return wait.ExponentialBackoff(backoff, func() (bool, error) { select { case <-ctx.Done(): return false, wait.ErrWaitTimeout default: return condition(ctx) } }) }
package core import ( "os"; "container/list"; "net"; "log"; "irc"; "runloop"; ) type Network struct { name string; server *server; clients *list.List; listen *listenConn; } func newNetwork(name string, serverConn net.Conn, listen net.Listener) *Network { var network *Network; accept := func(conn net...
{ for c := range network.clients.Iter() { c.(*client).Send(msg) } }
package misc import "errors" func Mkfifo(path string, mode uint32) (err error) { return errors.New("not supported") } func Mksocket(path string) (err error)
{ return errors.New("not supported") }
package main import ( "net/http" "github.com/go-chi/chi" ) type todosResource struct{} func (rs todosResource) Routes() chi.Router { r := chi.NewRouter() r.Get("/", rs.List) r.Post("/", rs.Create) r.Put("/", rs.Delete) r.Route("/{id}", func(r chi.Router) { r.Get("/", rs.Get) r.Put("/", rs....
{ w.Write([]byte("todo sync")) }
package actor type restartingStrategy struct{} func (strategy *restartingStrategy) HandleFailure(actorSystem *ActorSystem, supervisor Supervisor, child *PID, rs *RestartStatistics, reason interface{}, message interface{}) { logFailure(actorSystem, child, reason, RestartDirective) supervisor.RestartChildren(child)...
{ return &restartingStrategy{} }
package main import ( "fmt" _ "github.com/go-training/training/example16-init-func/bar" _ "github.com/go-training/training/example16-init-func/foo" ) var global = convert() func convert() int { return 100 } func main() { fmt.Println("global is", global) } func init()
{ global = 0 }
package main import "github.com/containerd/containerd/cmd/ctr/commands/shim" func init()
{ extraCmds = append(extraCmds, shim.Command) }
package filehash import ( "crypto/sha1" "fmt" "os" "github.com/cloudfoundry/gofileutils/fileutils" ) type Hash []byte func Zero() Hash { return Hash(make([]byte, sha1.Size)) } func New(filePath string) Hash { fileInfo, err := os.Lstat(filePath) if err != nil { panic(err) } if fileInfo.IsDir() { pani...
{ h1.Combine(h2) }
package main import "fmt" func main() { validate("aaaaa", "aaaaa", true) validate("aaaab", "aaaab", true) validate("aaaabc", "aaaab", false) validate("aaaa", "a*", true) validate("aaaabbb", "a*bbb", true) } func validate(s string, p string, want bool) { fmt.Printf("s: %s, p: %s, want: %t, got: %t\n", s, p, wan...
{ if len(p) == 0 { return len(s) == 0 } first := len(s) != 0 && (s[0] == p[0] || p[0] == '.') if len(p) > 1 && p[1] == '*' { return (first && IsMatch(s[1:], p)) || (IsMatch(s, p[2:])) } return first && IsMatch(s[1:], p[1:]) }
package conn import ( "fmt" "net" "sync" "sync/atomic" ) type ConnectRequest struct { id uint64 Address net.Addr Permanent bool Conn net.Conn state ConnectState lock sync.RWMutex retryCount uint32 } func (connectRequest *ConnectRequest) updateState(state ConnectState) { conne...
{ return atomic.LoadUint64(&connectRequest.id) }
package image import ( "github.com/dnephin/dobi/tasks/context" ) func RunRemove(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error)
{ removeTag := func(tag string) error { if err := ctx.Client.RemoveImage(tag); err != nil { t.logger().Warnf("failed to remove %q: %s", tag, err) } return nil } if err := t.ForEachTag(ctx, removeTag); err != nil { return false, err } if err := updateImageRecord(recordPath(ctx, t.config), imageModified...
package ivona_test import ( "log" ivona "github.com/jpadilla/ivona-go" ) func ExampleIvona_CreateSpeech() { client := ivona.New("IVONA_ACCESS_KEY", "IVONA_SECRET_KEY") options := ivona.NewSpeechOptions("Hello World") r, err := client.CreateSpeech(options) if err != nil { log.Fatal(err) } log.Printf("%v\n...
{ client := ivona.New("IVONA_ACCESS_KEY", "IVONA_SECRET_KEY") r, err := client.ListVoices(ivona.Voice{}) if err != nil { log.Fatal(err) } log.Printf("%v\n", len(r.Voices)) }
package wire import ( "bytes" "io" ) type fixedWriter struct { b []byte pos int } func (w *fixedWriter) Write(p []byte) (n int, err error) { lenp := len(p) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } n = lenp w.pos += copy(w.b[w.pos:], p) return } func newFixedWriter(max int) i...
{ return w.b }
package cloudguard import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type UpdateManagedListRequest struct { ManagedListId *string `mandatory:"true" contributesTo:"path" name:"managedListId"` UpdateManagedListDetails `contributesTo:"body"` IfMatch *string `mandatory:"false" contributesTo:"he...
{ return nil, false }
package main import ( "fmt" _ "ServiceTree/docs" _ "ServiceTree/routers" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func main() { if beego.RunMode == "dev" { beego.DirectoryIndex = true beego.StaticDir["/swagger"] = "swagger" } beego.Run() } func...
{ db_type := beego.AppConfig.String("database::db_type") db_user := beego.AppConfig.String("database::username") db_password := beego.AppConfig.String("database::password") db_host := beego.AppConfig.String("database::host") db_port := beego.AppConfig.String("database::port") db_name := bee...
package os const ( PathSeparator = '/' PathListSeparator = ':' ) func IsPathSeparator(c uint8) bool
{ return PathSeparator == c }
package floatingips import "github.com/gophercloud/gophercloud" const resourcePath = "floatingips" func rootURL(c *gophercloud.ServiceClient) string { return c.ServiceURL(resourcePath) } func resourceURL(c *gophercloud.ServiceClient, id string) string
{ return c.ServiceURL(resourcePath, id) }
package pes import "io" import "bytes" import "github.com/32bitkid/bitreader" type payloadReader struct { br bitreader.BitReader currentPacket *Packet remainder bytes.Buffer } func (r *payloadReader) Read(p []byte) (n int, err error) { for len(p) > 0 { cn, err := r.remainder.Read(p) n += cn...
{ return &payloadReader{ br: bitreader.NewReader(source), currentPacket: new(Packet), } }
package Plugin import "github.com/MPjct/GoMP/MySQLProtocol" type Plugin_interface interface { init(context MySQLProtocol.Context) read_handshake(context MySQLProtocol.Context) send_handshake(context MySQLProtocol.Context) read_auth(context MySQLProtocol.Context) send_auth(context MySQLProtocol.Context) read_aut...
{ return }
package builders import ( "time" "github.com/docker/docker/api/types" ) func Container(name string, builders ...func(container *types.Container)) *types.Container { container := &types.Container{ ID: "container_id", Names: []string{"/" + name}, Command: "top", Image: "busybox:latest", Status:...
{ p.Type = "udp" }
package matchers import ( "fmt" "github.com/bfontaine/go-tchoutchou/Godeps/_workspace/src/github.com/onsi/gomega/format" ) type SucceedMatcher struct { } func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) { return fmt.Sprintf("Expected success, but got an error:\n%s", format.Obj...
{ if actual == nil { return true, nil } if isError(actual) { return false, nil } return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) }
package uguis import ( "fmt" "os/exec" ) const serviceNameSimplePlayer = "simplePlayer" type simplePlayer struct { command string reqC chan PlayerRequest resC chan PlayerResponse closedReqC chan struct{} app *Application lgr Logger } func (p *simplePlayer) Play(req PlayerReque...
{ for req := range p.reqC { p.lgr.Print(NewLog( LogLevelINFO, p.app.Hostname, serviceNameSimplePlayer, fmt.Sprintf("%s by %s(@%s)", req.tweet.Text, req.tweet.User.Name, req.tweet.User.ScreenName), )) path := req.path if err := exec.Command(p.command, path).Run(); err != nil { p.logError(err) ...
package client import ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/v2" ) type UnexpectedHTTPStatusError struct { Status string } func (e *UnexpectedHTTPStatusError) Error() string { return fmt.Sprint...
{ return fmt.Sprintf("Error parsing HTTP response: %s: %q", e.ParseErr.Error(), string(e.Response)) }
package main import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/unrolled/render" ) var Render *render.Render func init() { Render = render.New(render.Options{ IndentJSON: true, }) } func index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") } func apiHa...
{ id := mux.Vars(r)["id"] fmt.Fprintf(w, "Welcome to the api Key hander page! %s", id) }
package fake import ( "encoding/json" "fmt" "net/http" "strings" . "github.com/onsi/gomega" "github.com/onsi/gomega/ghttp" ) type CFAPI struct { server *ghttp.Server } type CFAPIConfig struct { Routes map[string]Response } type Response struct { Code int Body interface{} } func NewCFAPI() *CFAPI { serv...
{ a.server.Close() }
package document type IndexingOptions int const ( IndexField IndexingOptions = 1 << iota StoreField IncludeTermVectors ) func (o IndexingOptions) IsIndexed() bool { return o&IndexField != 0 } func (o IndexingOptions) IncludeTermVectors() bool { return o&IncludeTermVectors != 0 } func (o IndexingOptions) Str...
{ return o&StoreField != 0 }
package log import ( "testing" ) type testLogger struct { keyvals []interface{} } type testSink struct { keyvals []interface{} } func (ts *testSink) Receive(keyvals ...interface{}) error { ts.keyvals = keyvals return nil } func TestLogger_Log(t *testing.T) { tl := &testLogger{} l := NewLogger(tl, nil) l...
{ tl.keyvals = keyvals return nil }
package tasks import ( "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/swag" strfmt "github.com/go-openapi/strfmt" ) type DeleteTaskParams struct { HTTPRequest *http.Request ID int64 } func (o *DeleteTaskParams) BindRequest(r *http.R...
{ var () return DeleteTaskParams{} }
package pdf417 import ( "image" "image/color" "github.com/boombuler/barcode" "github.com/boombuler/barcode/utils" ) type pdfBarcode struct { data string width int code *utils.BitList } func (c *pdfBarcode) Metadata() barcode.Metadata { return barcode.Metadata{barcode.TypePDF, 2} } func (c *pdfBarcode) Co...
{ if c.code.GetBit((y/moduleHeight)*c.width + x) { return color.Black } return color.White }
package model import "testing" func TestLocaleSyncKeys(t *testing.T)
{ l := Locale{} l.SyncKeys([]string{"testkey1", "testkey2"}) if _, ok := l.Pairs["testkey1"]; !ok { t.Fatal("expected 'testkey1' to be present") } if _, ok := l.Pairs["testkey2"]; !ok { t.Fatal("expected 'testkey2' to be present") } l.SyncKeys([]string{"testkey1"}) if _, ok := l.Pairs["testkey2"]; ok { ...
package object type Error string func (e Error) First() Value { return e } func (e Error) Rest() Value { return e } func (e Error) String() string { return string("<error: " + e + ">") } func (e Error) Type() Type
{ return ERROR }
package readline import "io" type Instance struct { t *Terminal o *Operation } type Config struct { Prompt string HistoryFile string } func NewEx(cfg *Config) (*Instance, error) { t, err := NewTerminal(cfg) if err != nil { return nil, err } rl := t.Readline() return &Instance{ t: t, o: rl, }, n...
{ return i.o.Stderr() }
package metrics import ( "github.com/cloudfoundry/dropsonde/metric_sender" ) var metricSender metric_sender.MetricSender var metricBatcher MetricBatcher type MetricBatcher interface { BatchIncrementCounter(name string) BatchAddCounter(name string, delta uint64) Close() } func Initialize(ms metric_sender.Metric...
{ if metricBatcher == nil { return } metricBatcher.BatchAddCounter(name, delta) }
package vox type Block uint8 const ( BlockNil = 0x00 blockActiveMask = 0x80 blockTypeMask = 0x7F ) func (b Block) Active() bool { return (blockActiveMask & b) == blockActiveMask } func (b Block) Activate(active bool) Block { if active { return b | blockActiveMask } return b & blockTypeMask } fu...
{ return &BlockBank{ typeMap: make(map[uint8]*BlockType), } }
package bauth_test import ( "github.com/insionng/macross" "github.com/insionng/macross/bauth" "testing" ) func TestBasicAuth(t *testing.T)
{ m := macross.New() m.Use(bauth.BasicAuth(func(username, password string) bool { if username == "inson" && password == "secret" { return true } return false })) go m.Run(":9999") }
package ast import ( "fmt" "github.com/rhysd/gocaml/token" "github.com/rhysd/locerr" ) type printPath struct { total int } func (v *printPath) VisitTopdown(e Expr) Visitor { fmt.Printf("\n -> %s (topdown)", e.Name()) return v } func Example() { src := locerr.NewDummySource("") rootOfAST := &Let{ Let...
{ fmt.Printf("\n -> %s (bottomup)", e.Name()) }
package jail import ( "bufio" "fmt" "os" ) type logReader struct { filename string file *os.File reader *bufio.Reader lines chan string errors chan error } func newLogReader(filename string) *logReader { f, err := os.Open(filename) if err != nil { fmt.Println(err) return nil } r := bufio....
{ line, err := l.reader.ReadString('\n') if err != nil { go func() { l.errors <- err }() } if line != "" { go func() { l.lines <- line }() } }
package issues import ( "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M)
{ unittest.MainTest(m, filepath.Join("..", ".."), "") }
package btcd import ( "os" "os/user" "path/filepath" "runtime" "strings" "unicode" ) func appDataDir(goos, appName string, roaming bool) string { if appName == "" || appName == "." { return "." } if strings.HasPrefix(appName, ".") { appName = appName[1:] } appNameUpper := string(unicode.ToUpper(r...
{ return appDataDir(runtime.GOOS, appName, roaming) }
package helper import ( "bufio" "net" ) type BufConn struct { net.Conn BR *bufio.Reader } func (c *BufConn) Peek(n int) ([]byte, error) { return c.BR.Peek(n) } func (c *BufConn) Read(b []byte) (n int, err error) { return c.BR.Read(b) } func (c *BufConn) Write(b []byte) (n int, err error) { return c.Conn.Wri...
{ c.Conn = conn }
package main func f(int) {} func h(int, int) {} func main() { f(g()) f(true) h(true, true) } func g() bool
{ return true }
package glib import "C" import "unsafe" type IActionMap interface { Native() uintptr LookupAction(actionName string) *Action AddAction(action IAction) RemoveAction(actionName string) } type ActionMap struct { *Object } func (v *ActionMap) Native() uintptr { return uintptr(unsafe.Pointer(v.native...
{ if v == nil || v.GObject == nil { return nil } return C.toGActionMap(unsafe.Pointer(v.GObject)) }
package lib import "sync" type ConcurrentPrinterMap struct { byCUPSName map[string]Printer byGCPID map[string]Printer mutex sync.RWMutex } func NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap { cpm := ConcurrentPrinterMap{} cpm.Refresh(printers) return &cpm } func (cpm *Conc...
{ c := make(map[string]Printer, len(newPrinters)) for _, printer := range newPrinters { c[printer.Name] = printer } g := make(map[string]Printer, len(newPrinters)) for _, printer := range newPrinters { if len(printer.GCPID) > 0 { g[printer.GCPID] = printer } } cpm.mutex.Lock() defer cpm.mutex.Unlock(...
package astar import ( "os" "image" ) import _ "image/png" func parseImage(img image.Image) MapData { max := uint32(65536-1) bounds := img.Bounds() map_data := NewMapData(bounds.Max.X, bounds.Max.Y) for y := bounds.Min.Y; y < bounds.Max.Y; y++ { for x := bounds.Min.X; x < bounds.Max.X; x++ { r, g, b, ...
{ f, err := os.Open(filename) if err != nil { return nil } defer f.Close() img, _, _ := image.Decode(f) return img }
package centos import ( "github.com/megamsys/libmegdc/templates" "github.com/megamsys/urknall" ) var centoshostinfo *CentosHostInfo func init() { centoshostinfo = &CentosHostInfo{} templates.Register("CentosHostInfo", centoshostinfo) } type CentosHostInfo struct{} func (tpl *CentosHostInfo) Options(t *temp...
{ p.AddTemplate("hostinfo", &CentosHostInfoTemplate{}) }
package TeleGogo import ( "encoding/json" "net/http" ) func responseToTgError(response *http.Response) TelegramError { defer response.Body.Close() tgErr := telegramError{} json.NewDecoder(response.Body).Decode(&tgErr) return tgErr } func errToTelegramErr(err error) TelegramError { return telegramError{OK: f...
{ return responseToTgError(response) }
package lock import ( "os" ) type LockedFile interface { File() *os.File Exclusive() bool Close() error } type DefaultLockedFile struct { f *os.File exclusive bool } func OpenExclusive(path string, flag int, perm os.FileMode) (LockedFile, error) { return open(path, flag, perm, true) } func OpenShare...
{ return e.exclusive }
package treemap import "github.com/emirpasic/gods/containers" func (m *Map) ToJSON() ([]byte, error) { return m.tree.ToJSON() } func (m *Map) FromJSON(data []byte) error { return m.tree.FromJSON(data) } func assertSerializationImplementation()
{ var _ containers.JSONSerializer = (*Map)(nil) var _ containers.JSONDeserializer = (*Map)(nil) }
package main import "./buildings" var board [2][2][][]buildings.Building func bget(x, y int) buildings.Building { xIndex, yIndex := 0, 0 if x < 0 { xIndex = 1 x = -x } if y < 0 { yIndex = 1 y = -y } return board[xIndex][yIndex][x][y] } func bset(x, y int, b buildings.Building) { xIndex, yIndex := 0,...
{ for xIndex := 0; xIndex <= 1; xIndex++ { for yIndex := 0; yIndex <= 1; yIndex++ { for x := xIndex; x < len(board[xIndex][yIndex]); x++ { for y := yIndex; y < len(board[xIndex][yIndex][x]); y++ { f(board[xIndex][yIndex][x][y], x, y) } } } } }
package auth import ( "encoding/base64" "github.com/outbrain/orchestrator/Godeps/_workspace/src/github.com/go-martini/martini" "net/http" "strings" ) type User string var BasicRealm = "Authorization Required" func Basic(username string, password string) martini.Handler { var siteAuth = base64.StdEncoding.E...
{ res.Header().Set("WWW-Authenticate", "Basic realm=\""+BasicRealm+"\"") http.Error(res, "Not Authorized", http.StatusUnauthorized) }
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: ...
{ copy := &Element{ text: e.text, parent: nil, children: make([]Node, 0), } for _, child := range e.children { copy.AddChild(child) } return copy }
package getter import ( "errors" "fmt" "github.com/goharbor/harbor/src/lib/orm" "github.com/goharbor/harbor/src/pkg/joblog" "github.com/goharbor/harbor/src/jobservice/errs" ) type DBGetter struct { } func NewDBGetter() *DBGetter { return &DBGetter{} } func (dbg *DBGetter) Retrieve(logID string) ([]byte,...
{ if len(logID) == 0 { return nil, errors.New("empty log identify") } jobLog, err := joblog.Mgr.Get(orm.Context(), logID) if err != nil { return nil, errs.NoObjectFoundError(fmt.Sprintf("log entity: %s", logID)) } return []byte(jobLog.Content), nil }
package main import ( "testing" ) func TestAvgScore(t *testing.T)
{ scores := []int{30, 60, 80, 100} exp := 67 act := avgScore(scores) if exp != act { t.Error("Expected", exp, "got", act) } }
package drive import ( "camlistore.org/pkg/blob" ) func (sto *driveStorage) StatBlobs(dest chan<- blob.SizedRef, blobs []blob.Ref) error
{ for _, br := range blobs { size, err := sto.service.Stat(br.String()) if err == nil { dest <- blob.SizedRef{Ref: br, Size: size} } else { return err } } return nil }
package obj import "fmt" const _SymKind_name = "SxxxSTEXTSELFRXSECTSTYPESSTRINGSGOSTRINGSGOFUNCSGCBITSSRODATASFUNCTABSELFROSECTSMACHOPLTSTYPERELROSSTRINGRELROSGOSTRINGRELROSGOFUNCRELROSGCBITSRELROSRODATARELROSFUNCTABRELROSTYPELINKSITABLINKSSYMTABSPCLNTABSELFSECTSMACHOSMACHOGOTSWINDOWSSELFGOTSNOPTRDATASINITARRSDATASBS...
{ if i < 0 || i >= SymKind(len(_SymKind_index)-1) { return fmt.Sprintf("SymKind(%d)", i) } return _SymKind_name[_SymKind_index[i]:_SymKind_index[i+1]] }
package validating import ( "io" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission/configuration" "k8s.io/apiserver/pkg/admission/plugin/webhook/generic" ) const ( PluginName = "ValidatingAdmissionWebhook" ) type Plugin struct { *generic.Webhook } var _ admission.ValidationInterface = &Plu...
{ plugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) { plugin, err := NewValidatingAdmissionWebhook(configFile) if err != nil { return nil, err } return plugin, nil }) }
package servo_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" "github.com/fgrosse/servo" "fmt" ) func TestServo(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Servo Test Suite") } type TestBundle struct {} func (b *TestBundle) Boot(kernel *servo.Kernel) { kernel.Regist...
{ return &SomeService{} }
package chart import ( "bytes" "github.com/golang/protobuf/jsonpb" ) func (msg *Config) MarshalJSON() ([]byte, error) { var buf bytes.Buffer err := (&jsonpb.Marshaler{ EnumsAsInts: false, EmitDefaults: false, OrigName: false, }).Marshal(&buf, msg) return buf.Bytes(), err } func (msg *Value) Ma...
{ return (&jsonpb.Unmarshaler{ AllowUnknownFields: false, }).Unmarshal(bytes.NewReader(b), msg) }
package utils import ( "fmt" "strings" "github.com/SaferLuo/EtherIOT/node" "github.com/SaferLuo/EtherIOT/rpc" "gopkg.in/urfave/cli.v1" ) func NewRemoteRPCClient(ctx *cli.Context) (rpc.Client, error) { if ctx.Args().Present() { endpoint := ctx.Args().First() return NewRemoteRPCClientFromString(endpoint) ...
{ if strings.HasPrefix(endpoint, "ipc:") { return rpc.NewIPCClient(endpoint[4:]) } if strings.HasPrefix(endpoint, "rpc:") { return rpc.NewHTTPClient(endpoint[4:]) } if strings.HasPrefix(endpoint, "http:") { return rpc.NewHTTPClient(endpoint) } if strings.HasPrefix(endpoint, "ws:") { return rpc.NewWSClien...
package main import "fmt" func main() { rmbNum := make(map[int]int) only89 := []int{} rmbNum[89] = 89 rmbNum[1] = 1 for i := 1; i < 10000000; i++ { yes := false rmbSeq := []int{} for num := i; ; num = findNext(num) { rmbSeq = append(rmbSeq, num) if val, ok := rmbNum[num]; ok { if val == 89 { ...
{ var newNum int for num > 0 { digit := num % 10 newNum += digit * digit num /= 10 } return newNum }
package main import ( "fmt" "time" "github.com/lxc/lxd/client" ) func cmdShutdown(args *Args) error
{ c, err := lxd.ConnectLXDUnix("", nil) if err != nil { return err } _, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "") if err != nil { return err } chMonitor := make(chan bool, 1) go func() { monitor, err := c.GetEvents() if err != nil { close(chMonitor) return } monitor.Wait() ...
package lemon import ( "errors" "testing" ) func TestOption(t *testing.T) { tests := map[string]TestHandler{ "WithError": OptionWithError, } for name, handler := range tests { t.Run(name, Setup(handler)) } } type errOption struct { err error } func OptionWithError(runtime *TestRuntime) { expected :=...
{ return o.err }
package mailru import ( "encoding/json" "errors" "strings" "time" "github.com/markbates/goth" ) type Session struct { AuthURL string AccessToken string RefreshToken string ExpiresAt time.Time } func (s *Session) GetAuthURL() (string, error) { if s.AuthURL == "" { return "", errors.New(goth.No...
{ sess := new(Session) err := json.NewDecoder(strings.NewReader(data)).Decode(&sess) return sess, err }